我正在尝试使用 ~ (波浪号)运算符连接 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错误,连接进行得很顺利....
最佳答案
您可以使用 set 标记将字符串与变量连接起来。从您的示例中,我们可以重写这些行,
{% set class = 'original_text' %}
{% set class = class ~ ' some_other_text'%}
我们可以通过打印这样的新类变量来显示,
{{class}}
它会像这样显示输出, original_text some_other_text
关于variables - 将文本 append 到 Twig 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21848745/