Twig: prevent parsing of client-side templates

末鹿安然 提交于 2019-12-18 10:48:10

问题


I need to output a portion of client-side handlebars templates, which has tags similar to twig's 'say' tags:

  <script type="text/x-handlebars">
    {{#view App.MyView}}
      <h1>Hello world!</h1>
    {{/view}}
  </script>

And twig attempts to parse these templates. How do I prevent it? Is it possible to mark a section of a template as plain text?


回答1:


There is raw tag for this purpose:

<script type="text/x-handlebars">
  {% raw %}
    {{#view App.MyView}}
      <h1>Hello world!</h1>
    {{/view}}
  {% endraw %}
</script>

Update

As raw tag is deprecated use verbatim instead.




回答2:


{% raw %} deprecated

{% verbatim %}
    <ul>
    {% for item in seq %}
        <li>{{ item }}</li>
    {% endfor %}
    </ul>
{% endverbatim %}

Source: http://twig.sensiolabs.org/doc/tags/verbatim.html




回答3:


For bigger blocks of templates I would suggest to move those script templates into a separate file/files (where I suppose they should be to make all more structured).

Then render templates in your twig by using source command {{ source('uploadables-js.html') }} (IMPORTANT, no 'use' or 'include').




回答4:


To not litter templates with raw or verbatim tags, one can change lexar options to not conflict with client side template engines:

...
$lexer_options = [
  'tag_variable' => ['{~', '~}'],
];
$lexer = new Twig_Lexer($twig, $lexer_options);
$twig->setLexer($lexer);


来源:https://stackoverflow.com/questions/9443313/twig-prevent-parsing-of-client-side-templates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!