dpdkqls6399
dpdkqls6399
2018-02-13 19:23

使用块将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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongsi2317 dongsi2317 3年前

    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 %}
    

    See TwigFiddle

    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.

    点赞 评论 复制链接分享