dpdkqls6399 2018-02-13 19:23
浏览 167
已采纳

使用块将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 2018-02-13 20:36
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?