[英]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. 我知道如何访问资产,但是我想创建一个使用Javascript和Twig的模板,这将允许我在脚本中使用Twig变量。
For example, I have a template called 'details.html.twig', which extends a 'layout.html.twig': 例如,我有一个名为“ details.html.twig”的模板,该模板扩展了一个“ 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'. 所有这些都完美地工作了,但是为了能够重用一些js代码(使用twig变量),我剪切了一部分脚本并将其放在一个名为'viewer.html.twig'的外部模板中。 To be able to use it in my 'details.html.twig', I used:
为了能够在我的“ details.html.twig”中使用它,我使用了:
{% include '@AcmeBundle/Front/Model/viewer.html.twig' %}
I put this line right after the {{ parent() }} one and before the <script>
tag. 我将这一行放在{{parent()}}之后,在
<script>
标记之前。 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 杰蒂·杰伊(G'day)
If you code a file containing only javascript you should name your file: 如果您编码的文件仅包含javascript,则应命名文件:
{% include '@AcmeBundle/Front/Model/viewer.js.twig' %}
Then Twig (as of 1.17) automatically defines its escaping strategy based on the extension. 然后Twig(从1.17版本开始)根据扩展名自动定义其转义策略。
See the twig docs and an example of js twig file in symfony . 请参阅symfony中的twig文档和js twig文件示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.