Generate Twig Template from Twig Template? (CodeGenerator)

我怕爱的太早我们不能终老 提交于 2021-01-29 14:40:17

问题


I write a code generator in Symfony2 with twig.

My problem is: I want to create a twig template with a twig template.

For a better understanding here an example: I have a twig file that is a template for a PHP Page - so if i run it it generates me PHP code from that twig template. (ex. a Controller for CRUD)

Now I want to generate the view template - but how can i tell twig to use the commands I need for generation and let the dynamic parts for the template as is?

Can I change how the tags are formed? Can I change {{ varname }} in [[ varname ]] ?

THX for your help


回答1:


Of course you can!, take the Sensio CRUD generator as an example:

  • https://github.com/sensiolabs/SensioGeneratorBundle/blob/master/Resources/skeleton/crud/views/index.html.twig.twig
  • http://symfony.com/doc/current/bundles/SensioGeneratorBundle/commands/generate_doctrine_crud.html

To prevent the rendering of some parts you can:

  • Use strings as the SensioGeneratorBundle does.
  • Use the verbatim tag to prevent the parsing of some parts (http://twig.sensiolabs.org/doc/tags/verbatim.html)
  • Change the syntax as you are suggesting (http://twig.sensiolabs.org/doc/recipes.html#customizing-the-syntax)

You might find the same issue working with AngularJS in Twig templates:

  • AngularJS-Twig conflict with double curly braces
  • Angularjs on a symfony2 application



回答2:


I think you are looking for the {% verbatim %} tag.

Verbatim let you write Twig code without interpretation, for example:

{% verbatim %}
  {% for key, value in array %}
    {{ value }}
  {% endfor %}
{% endverbatim %}

Will literally output:

  {% for key, value in array %}
    {{ value }}
  {% endfor %}


来源:https://stackoverflow.com/questions/23849951/generate-twig-template-from-twig-template-codegenerator

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