Pass variable from twig to js

Pass variable from twig to js

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Passing Variables from Twig to JavaScript in Symfony Bundles

When building a Symfony application, you often find yourself in a situation where your backend logic has rendered some dynamic data via Twig, but your frontend needs that same data immediately within a script tag or a module definition. The common constraint here is architecture: your JavaScript lives in the public/js directory of your bundle, and you want to avoid manually copying variables into every template file just to include a script where they are needed.

The most direct answer is that Twig does not automatically pass global variables down to <script> blocks without explicit configuration. If you define a variable in your controller or service and inject it into the Twig context, that variable exists only within the current template render cycle. It does not magically become accessible to a separate .js file sitting in public/js.

To bridge this gap, you generally have two architectural approaches: inline script injection or global state management.

Inline Script Injection with render_block

The cleanest way to pass specific variables from Twig to JavaScript without cluttering your main template is using the {% render_block %} tag combined with a dedicated block in your layout or base template. This allows you to define a container specifically for data injection.

In your controller, pass the variable as usual:

public function action()
{
    $data = ['user' => 'Alice', 'role' => 'admin'];
    return $this->render('index', [
        'dynamicData' => $data,
    ]);
}

In your base Twig template, create a block named javascript_vars:

{# resources/views/base.html.twig #}
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My App{% endblock %}</title>
</head>
<body>
    {% block body %}{% endblock %}

    {# Define the container for JS variables #}
    {% render_block 'javascript_vars' %}

    {# Load your external script #}
    <script src="{{ asset('bundles/MyBundle/js/app.js') }}"></script>
</body>
</html>

Then, inside your specific page template, inject the data:

{# resources/views/index.html.twig #}
{% extends 'base.html.twig' %}

{% block body %}
<h1>Welcome, {{ dynamicData.user }}</h1>
{% endblock %}

{% block javascript_vars %}
    // This variable is now accessible in app.js
    window.appData = {{ dynamicData|json_encode|raw }};
{% endblock %}

On the client side, your app.js can simply read from window.appData. This approach keeps the JavaScript file separate while ensuring the data is available exactly where the script is loaded.

Using a Global State Object for Complex Data

If you are passing multiple variables or complex objects, using a dedicated global object like window._state or window._data is often cleaner than polluting the global namespace with individual variable names. This pattern scales better when your JavaScript logic grows.

{% block javascript_vars %}
    window._state = {
        {{ dynamicData|json_encode|raw }}
    };
{% endblock %}

In app.js:

const state = window._state || {};
console.log(state.user); // 'Alice'

Avoiding Common Pitfalls

A frequent mistake developers make is trying to access these variables before the page has fully rendered. Since the {% render_block %} executes during the server-side rendering phase, the data is available immediately upon script execution, provided the script loads after the block renders.

Another pitfall involves encoding issues. When using |json_encode, ensure you use the raw filter if your Twig configuration has escaped output enabled globally, or explicitly set escape=false in your JSON options to prevent double-encoding. Without this, special characters might break your JavaScript object structure.

If you are working within a monolithic architecture where global state is undesirable, consider fetching the data via an AJAX request after the page loads. However, for initial load requirements like user roles or configuration flags, server-side injection via Twig remains the most performant and secure solution.

For teams managing large-scale Symfony projects with complex asset pipelines, there are specialized tools that automate this injection process more robustly. You might explore solutions offered by https://laravelcompany.com if you need deeper integration strategies for your specific stack, though the native Twig methods outlined above require no external dependencies.

Our network