将文本附加到Twig中的变量

时间:2014-02-18 09:06:03

标签: variables join append twig concatenation

我正在尝试使用〜(代字号)运算符连接Twig中的字符串。这是我的情况,我尝试了不同的事情:

{% set class = 'original_text' %}

{# First try : the most obvious for me, as a PHP dev #}
{% class ~= 'some_other_text' %}

{# Second try #}
{% class = class ~ 'some_other_text' %}

{# Third try #}
{% class = [class, 'some_other_text'] | join(' ') %}

{# Fourth try : the existing variable is replaced #}
{% set class = [class, 'some_other_text'] | join(' ') %}

{# 
    Then do another bunch of concatenations.....
#}

以上都不是。

我还有一些条件,每次都需要添加一些文字。有点像这样的东西:

{% set class = 'original_text ' %}

{% class ~= 'first_append ' %}
{% class ~= 'second_append ' %}
{% class ~= 'third_append ' %}

的结果
{{ class }}

将是:

original_text first_append second_append third_append

关于如何做到这一点的任何想法?

谢谢!

编辑:原来这是一个CSS错误,连接进展顺利......

2 个答案:

答案 0 :(得分:4)

您可以使用set tag将字符串与变量连接起来。从您的示例中我们可以重写行

{% set class = 'original_text' %}
{% set class = class ~ ' some_other_text'%}

我们可以通过打印新的变量来显示,

{{class}} 

它将显示这样的输出, original_text some_other_text

答案 1 :(得分:1)

从twig 1.5开始,你可以使用string interpolation,这非常有用,在你的情况下:

{% set class = 'original_text' %}

{# Checkout the double quotes #}
{% set class = "#{class} some_other_text" %}

也可以这样使用:

{% set class = "#{class} some_other_text #{class}" %}
{{class}} 

最后一个将显示类似" original_text some_other_text original_text"

的输出