Twig variable in external JS file

There a two approaches when you need to pass a twig variable to an external javascript file

  1. Define the variables inside a script block in the twig template
<!DOCTYPE html>
<html>
   <head>
      <title></title>
   </head>
   <body>
       <script>
           var my_twig_var = {% if twig_var is defined %}'{{ twig_var }}'{% else %}null{% endif %}
       </script>
       <script src="scripts/functions.js"></script>
   </body>
</html>

For this approach I usally add a block called “javascript” block in my main/base template

base.twig.html

<!DOCTYPE html>
<html>
   <head>
      <title></title>
   </head>
   <body>
       {% block body %}
       {% endblock %}
       {% block javascript %}
       {% endblock %}
   </body>
</html>

page.html.twig

{% extends base.twig.html %}
{% block body%}
    <h1>Hello World</h1>
{% endblock %}
{% block javascript %}
    <script>
      alert('{{ twig_var|default('Hello World') }}');
    </script>
{% endblock %}

  1. Pass the variables to javascript with the aid of data-* attributes
<div data-foo="{{ foo }}">...</div>
$(function() {
    $(document).on('click', '.button', function(e) {
        console.log($('div[data-foo]').data('foo'));
    });
});

Sidenote: if you want to pass an object or an array to twig you can always use the json_encode filter, which will convert the variable to a valid javascript object

If you want to have control over which object properties are exposed by the json_encode filter you can always implement the interface Serializable

Leave a Comment