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 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分