使用块将Smarty 3转换为Twig 2
hopefully this will be my last point of confusion.
In my Smarty templates I have what equates to the twig code below which sets the 'heading' block conditionally depending on what 'show' is set to. The template code I have inserted below doesn't work, it gives an error saying that the heading block is already defined. I did some research and I figured out that this doesn't work with Twig, I guess because it is compiling it before it is checking the if statement which to me is totally counter intuitive but I didn't create Twig. =)
{% if show is defined %}
{% if show == 'add_form' %}
{% block heading %}Add{% endblock %}
{% elseif show == 'main' %}
{% block heading %}Main{% endblock %}
{% endif %}
I only use this style in templates where there are a bunch of very tiny views (literally 2-3 lines of HTML) so I suppose that I could just make separate template files for each of them but that just seems like a ton of extra files. What is the "right" way to do this in Twig?
Thanks again
希望这将是我最后的困惑点。 p>
在我的Smarty模板中,我有什么等同于下面的树枝代码,它根据设置的'show'有条件地设置'heading'块。 我在下面插入的模板代码不起作用,它给出了一个错误,说明已经定义了标题块。 我做了一些研究,我发现这不适用于Twig,我想是因为它在检查if语句之前编译它对我来说完全反直觉但我没有创建Twig。 =) p>
{%if show is defined%}
{%if if show =='add_form'%}
{%block heading%}添加{%endblock% }
{%elseif show =='main'%}
{%block heading%} Main {%endblock%}
{%endif%}
code> pre>
再次感谢 p>
div>
Right, you can't define the same block multiple times, even if they are in separate logical branches.
These both work:
{% if show is defined %}
{% block heading %}
{% if show == 'add_form' %}
Add
{% elseif show == 'main' %}
Main
{% endif %}
{% endblock %}
{% endif %}
{% block heading %}
{% if show is defined %}
{% if show == 'add_form' %}
Add
{% elseif show == 'main' %}
Main
{% endif %}
{% endif %}
{% endblock %}
I think the second one is clearer (at least in this case), because a template that extends another one cannot include contents outside Twig blocks. What this means is that if you try to do something like this:
{% extends 'layout.twig' %}
{% block heading %}
Some content
{% endblock %}
Hello world!
You'll get a Twig_Error_Syntax
exception with this message:
A template that extends another one cannot include contents outside Twig blocks. Did you forget to put the contents inside a
{% block %}
tag?
So, the template stays clear if you put all code inside blocks.