Search code examples
symfonytwigassetic

How can I use a Twig variable in Assetics 'javascript' tag?


I'm using Assetic to include my scripts and need to pass the current locale. How would I do that?

{% javascripts
    '@MyBundle/Resources/public/components/moment/moment.js'
    '@MyBundle/Resources/public/components/moment/lang/' ~ app.request.locale ~ '.js'
 %}

String concatenation does not work and throws Unexpected token "operator" of value "~"


Solution

  • You can use assetic's variables as described in Ryan Weaver's answer here. The feature is kind of broken but will work in your case as you use the locale as variable.

    The answer is that only two variables work by default (locale and env, and their values are preconfigued in Symfony: https://github.com/symfony/AsseticBundle/blob/master/DefaultValueSupplier.php#L31.

    config_dev.yml

    assetic:
        use_controller: false
    

    config.yml

    You'll also need to set your assetic.variables.locale [...] to the total possible combinations of your variable:

    assetic:
        variables:
            locale:    [en,fr,de]
    

    ... then use them inside the javaScripts tag after invoking assetic:dump.

    template

    {% javascripts
         'bundles/my/components/{locale}.js'
    %}