【问题标题】:Appending a text to a variable in Twig将文本附加到 Twig 中的变量
【发布时间】:2014-03-17 21:50:07
【问题描述】:

我正在尝试使用 ~(波浪号)运算符连接 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 错误,连接进行得很顺利....

【问题讨论】:

    标签: variables join append twig concatenation


    【解决方案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”的输出

    【讨论】:

      【解决方案2】:

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

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

      我们可以像这样打印新的class变量来展示,

      {{class}} 
      

      它会像这样显示输出,original_text some_other_text

      【讨论】:

      • 谢谢,但正如我所说,有几个串联要做。如果我做一个或多个额外的集合 class=.... ,之前的连接就会丢失
      • 事实上,这是一个 CSS 错误,连接是正确的......我接受你的回答,这是正确的做法!
      猜你喜欢
      • 2012-09-09
      • 2014-08-04
      • 1970-01-01
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      • 2021-11-29
      相关资源
      最近更新 更多