简体   繁体   中英

How to include properly Javascript using a Javascript Twig Template

I know how to access my assets, but i wanted to create a template working with Javascript and Twig, which would allow me to use Twig variables in my script.

For example, I have a template called 'details.html.twig', which extends a 'layout.html.twig':

{% extends '@AcmeBundle/Front/layout.html.twig %}
{# SOME CODE AND CONTENT #}


{% block page_script %}
  {{ parent() }}
  <script>
    {# Part of my script #}
  </script>
{% endblock page_script %}

All of this worked perfectly, but to be able to reuse some js code (using twig variables), I cut some part of my script and put I in an external template, called 'viewer.html.twig'. To be able to use it in my 'details.html.twig', I used:

{% include '@AcmeBundle/Front/Model/viewer.html.twig' %}

I put this line right after the {{ parent() }} one and before the <script> tag. However, my script which used to work when directly written in 'details' template seems to be quite ignored right now.

If any of you could have a clue of what makes my template being included but skipped, or a way to include the template easier or properly, I'm open to all kind of observations.

G'day, Jérémy

If you code a file containing only javascript you should name your file:

{% include '@AcmeBundle/Front/Model/viewer.js.twig' %}

Then Twig (as of 1.17) automatically defines its escaping strategy based on the extension.

See the twig docs and an example of js twig file in symfony .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM