Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Javascript Context Laravel Package

becklyn/javascript-context

Send server-side data from PHP to JavaScript via a Twig helper that renders a JSON script container. Set values through the JavaScriptContext service and optionally use context providers/domains to inject shared data automatically.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package

    composer require becklyn/javascript-context
    

    Ensure your Laravel project uses Symfony 5+ (Laravel 8+ is compatible by default).

  2. Register a Provider (Optional but Recommended) Create a service provider to inject global JavaScript context data:

    // app/Providers/JavaScriptContextProvider.php
    namespace App\Providers;
    
    use Becklyn\JavaScriptContext\Context\JavaScriptContext;
    use Becklyn\JavaScriptContext\Provider\ContextProviderInterface;
    use Illuminate\Support\ServiceProvider;
    
    class JavaScriptContextProvider extends ServiceProvider implements ContextProviderInterface
    {
        public function register()
        {
            $this->app->bind(ContextProviderInterface::class, self::class);
        }
    
        public function provideJavaScriptContext(JavaScriptContext $context, ?string $domain): void
        {
            $context->set('app_name', config('app.name'));
            $context->set('user', auth()->user()?->toArray());
        }
    }
    

    Register it in config/app.php under providers.

  3. First Use Case: Pass Data to JavaScript Inject JavaScriptContext into a controller or service:

    use Becklyn\JavaScriptContext\Context\JavaScriptContext;
    
    public function show(JavaScriptContext $context)
    {
        $context->set('dynamic_data', ['key' => 'value']);
        return view('welcome');
    }
    
  4. Render in Blade/Twig Add the context to your template:

    {{- javascript_context("app") -}}
    

    Or in Blade (if using Twig):

    @twig('javascript_context("app")')
    
  5. Access in JavaScript Parse the data in your frontend:

    const data = JSON.parse(
        document.getElementById("_javascript-context").textContent
            .replace(/&lt;/g, "<")
            .replace(/&gt;/g, ">")
            .replace(/&amp;/g, "&")
    );
    console.log(data.dynamic_data);
    

Implementation Patterns

Core Workflows

1. Domain-Specific Contexts

Use the $domain parameter to segment data (e.g., app, admin):

// Controller
$context->set('admin_settings', [...], 'admin');
{# Admin panel #}
{{- javascript_context("admin") -}}

2. Dynamic Data Injection

Attach runtime data (e.g., flash messages, API responses):

public function store(Request $request, JavaScriptContext $context)
{
    $context->set('flash', ['success' => 'Item created!']);
    return redirect()->back();
}

3. Service-Layer Integration

Decouple context logic from controllers:

// app/Services/ContextService.php
class ContextService
{
    public function __construct(private JavaScriptContext $context) {}

    public function setUserData(): void
    {
        $this->context->set('user', auth()->user()?->toArray());
    }
}

Use in controllers:

public function __construct(private ContextService $contextService) {}

public function index()
{
    $this->contextService->setUserData();
    return view('dashboard');
}

4. Twig/Blade Integration

  • Blade (if using Twig bridge):
    @twig('javascript_context("app")')
    
  • Custom Blade Directive (for non-Twig setups):
    // app/Providers/BladeServiceProvider.php
    Blade::directive('jsContext', function ($domain) {
        return "<?php echo Becklyn\JavaScriptContext\Twig\JavaScriptContextExtension::renderContext($domain); ?>";
    });
    
    Usage:
    @jsContext('app')
    

5. Provider Chaining

Combine multiple providers for layered data:

// app/Providers/AuthContextProvider.php
class AuthContextProvider implements ContextProviderInterface
{
    public function provideJavaScriptContext(JavaScriptContext $context, ?string $domain): void
    {
        if ($domain === 'app') {
            $context->set('auth', auth()->only('id', 'name'));
        }
    }
}

Integration Tips

Laravel-Specific Optimizations

  1. Leverage Laravel’s Service Container Bind the context to a facade for cleaner syntax:

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        app()->singleton('jsContext', function () {
            return app(JavaScriptContext::class);
        });
    }
    

    Usage:

    jsContext()->set('key', 'value');
    
  2. Middleware for Global Context Attach data to every request:

    // app/Http/Middleware/SetJavaScriptContext.php
    public function handle($request, Closure $next)
    {
        app(JavaScriptContext::class)->set('request_id', $request->id());
        return $next($request);
    }
    
  3. Vue/React Integration Expose context as a global variable:

    window.jsContext = JSON.parse(
        document.getElementById("_javascript-context").textContent
            .replace(/&lt;/g, "<")
            .replace(/&gt;/g, ">")
            .replace(/&amp;/g, "&")
    );
    

    Use in Vue:

    export default {
        computed: {
            user() {
                return window.jsContext.user;
            }
        }
    };
    
  4. Testing Mock the context in tests:

    $context = Mockery::mock(JavaScriptContext::class);
    $context->shouldReceive('set')->with('test', 'value');
    $this->app->instance(JavaScriptContext::class, $context);
    

Gotchas and Tips

Pitfalls

  1. HTML Escaping Quirks

    • Only <, >, and & are escaped. If your data contains " or ', it may break JSON parsing.
    • Fix: Use json_encode() in PHP to ensure safe strings:
      $context->set('html_content', json_encode('<div>Safe</div>'));
      
      Then decode in JS:
      const safeHtml = JSON.parse(data.html_content);
      
  2. Domain Mismatches

    • Providers check $domain strictly. A typo (e.g., "app" vs "APP") will skip data injection.
    • Fix: Normalize domains in providers:
      if (strtolower($domain) === 'app') { ... }
      
  3. Twig Dependency

    • The package assumes Twig. For Blade-only projects:
      • Use the Twig bridge or create a custom Blade directive (see Implementation Patterns).
      • Alternative: Manually render the context in Blade:
        <script id="_javascript-context" class="js-context">
            {{ json_encode($javascriptContextData) }}
        </script>
        
  4. Service Provider Tagging

    • Forgetting to tag providers (javascript_context.provider) will prevent them from running.
    • Fix: Use autoconfiguration (Laravel 8+) or manually tag:
      # config/services.yaml
      services:
          App\Providers\MyProvider:
              tags: ['javascript_context.provider']
      
  5. Performance with Large Data

    • Injecting massive payloads (e.g., entire database dumps) bloats the DOM.
    • Fix: Lazy-load data via API endpoints or use ->set() selectively.
  6. Symfony 5 Dependency

    • While Laravel 8+ handles Symfony 5, older Laravel versions may conflict if the package pulls in Symfony components.
    • Fix: Check composer.json for symfony/* dependencies and pin versions:
      "require": {
          "symfony/http-client": "^5.0"
      }
      

Debugging Tips

  1. Inspect Rendered Output Check the DOM for the context container:

    console.log(document.getElementById("_javascript-context").textContent);
    
  2. Provider Debugging Log provider execution:

    public function provideJavaScriptContext(JavaScriptContext $context, ?string $domain): void
    {
        \Log::debug("Provider running for domain: $domain");
        $context->set('debug', ['domain' => $domain]);
    }
    
  3. JSON Parsing Errors

    • If JSON.parse() fails, the data may contain unescaped characters.
    • Fix: Use a helper function:
      function parseJsContext() {
          const text = document.getElementById("_javascript-context").textContent
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky