2017-05-19 18 views
-1

我在枝條模板中有一個if/else條件,它切換代碼塊的out標籤,但內部塊是相同的。有沒有辦法在不創建單獨文件的情況下減少重複?
這是我的時刻:如何減少枝條模板中的重複

{% if condition %} 
    <a href=""> 
     {{ content }} 
    </a> 
{% else %} 
    <span> 
     {{ content }} 
    </span> 
{% endif %} 

我希望做一些事情,如:

{% if condition %} 
    <a href=""> 
     {% include mycontent %} 
    </a> 
{% else %} 
    <span> 
     {% include mycontent %} 
    </span> 
{% endif %} 

{% mycontent %} 
    {{ content }} 
{% endmycontent %} 

這種事可能嗎?

+0

地方'{{內容}}'文件中'content.twig.html'並切換到'{%包括「content.twig。 html「%}' – DarkBee

+0

有沒有辦法做到這一點沒有額外的文件? – Votemike

回答

2

如果你不想使用額外的文件,你可以使用宏的:

{% import _self as macro %} 

{% macro foo(content) %} 
    {{ content }} 
{% endmacro %} 

{% for condition in [0, 1, 0, 1, ] %} 
    {% if condition %} 
     <a href="">{{ macro.foo('Bar') }}</a> 
    {% else %} 
     <span>{{ macro.foo('Bar') }}</span> 
    {% endif %} 
{% endfor %} 

fiddle

0

你想要做的事情必須使用正常的語法來完成。一個額外的文件。幷包含此文件。

但是,如果你想這樣做沒有額外的文件。使用{%集variablecontent = 「把這裏的內容」 %},然後在你的 「{%爲myContent%}」 部分ü把{{variablecontent}}

希望這有助於

+0

這可以用於較小的內容,但我的內容略大。不過謝謝。 – Votemike

+0

@Votemike認爲如此 –