Samuel
Samuel

Reputation: 925

TWIG - Include different JS asset file depending to a variable

I would like to load different JavaScript files in a Twig template depending to a variable setup before.

And i try to do something like that :

{% set myFileToLoad = 'awesomeScript.js' %}

{% javascripts
    'js/forms/' ~ myFileToLoad
%}
    <script  src="{{ asset_url }}"></script>
{% endjavascripts %}

But I got this error each time I try to edit the name of the asset :

Attempted to call an undefined method named "getFilename" of class "Twig\TokenStream".

Is there a way to do it better ? Thank you in advance

Upvotes: 1

Views: 1164

Answers (1)

msg
msg

Reputation: 8161

You seem to be using an old syntax based on the assetic bundle that is no longer supported on Symfony >= 4.0, but you can use standard blocks instead, and are pretty close to getting it right:

{% set myFileToLoad = 'awesomeScript.js' %}

{% block javascripts %}
    <script src="{{ asset('js/forms/' ~ myFileToLoad) }}"></script>
{% endblock %}

Upvotes: 1

Related Questions