Variables 将文本追加到细枝中的变量

Variables 将文本追加到细枝中的变量,variables,join,append,twig,concatenation,Variables,Join,Append,Twig,Concatenation,我正在尝试使用~(tilde)操作符连接细枝中的字符串。以下是我的案例,我尝试了不同的方法: {% 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 #} {% c

我正在尝试使用~(tilde)操作符连接细枝中的字符串。以下是我的案例,我尝试了不同的方法:

{% 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错误,连接进行得很顺利。

您可以使用set标记将字符串与变量连接起来。根据你的例子,我们可以重写这些行

{% set class = 'original_text' %}
{% set class = class ~ ' some_other_text'%}
我们可以通过如下方式打印新的类变量来显示

{{class}} 

它会像这样显示输出,原始文本一些其他文本

因为您可以使用twig 1.5,这在您的情况下非常有用:

{% 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”

谢谢,但正如我所说的,有几个连接需要完成。如果我做一个或多个额外的集合类=,以前的连接已丢失事实上,这是一个CSS错误,连接已正确进行。。。我接受你的回答,这是正确的选择!