如何在Twig中连接字符串

543

有人知道如何在Twig中连接字符串吗?我想做类似于:

{{ concat('http://', app.request.host) }}
11个回答

1037

这应该能正常工作:

{{ 'http://' ~ app.request.host }}

要在同一标签中添加过滤器(如'trans'),请使用:

{{ ('http://' ~ app.request.host) | trans }}

正如Adam Elsodaney指出的那样,您还可以使用字符串插值,但需要使用双引号括起来:

{{ "http://#{app.request.host}" }}

4
谢谢你的回答。但是似乎 | trans 过滤器在这里不起作用(例如:{{ 'test_' ~ name | trans }} 无法翻译我的项目)。你有什么想法吗?谢谢! - guillaumepotier
14
是的,你需要创建一个变量来保存连接后的字符串。例如:{% set foo = 'http://' ~ app.request.host %}。然后你可以这样使用:{{ foo | trans }} - Alessandro Desantis
78
一行翻译:{{ ('test_' ~ name) | trans }} --> {{ ('测试_' ~ name) | trans }} - Johnny
7
谢谢。问题在于过滤器的优先级高于连接运算符。 - Alessandro Desantis
谢谢!在拼接中加上括号有助于转换。 - trickyzter
显示剩余3条评论

114

还有一个鲜为人知的Twig功能是字符串插值

{{ "http://#{app.request.host}" }}

28
不错的功能。请注意,只能使用双引号字符串! - bzeaman

33

你要找的运算符是波浪号(~),就像Alessandro所说的那样,在文档中可以找到:

~:将所有操作数转换为字符串并将它们连接起来。{{ "Hello " ~ name ~ "!" }} 将返回(假设name是'John')Hello John!。- http://twig.symfony.com/doc/templates.html#other-operators

这里还有一个例子在文档的其他地方

{% set greeting = 'Hello' %}
{% set name = 'Fabien' %}

{{ greeting ~ name|lower }}   {# Hello fabien #}

{# use parenthesis to change precedence #}
{{ (greeting ~ name)|lower }} {# hello fabien #}

22
在这种情况下,如果你想输出纯文本和一个变量,你可以像这样做:
http://{{ app.request.host }}

如果您想要将一些变量连接起来,alessandro1997的解决方案会更好。


2
这对我不起作用,因为我必须使用另一个过滤器对整个字符串进行URL编码... - stoefln

16
{{ ['foo', 'bar'|capitalize]|join }}

您可以看到,这适用于过滤器和函数,而无需在单独的行上使用set


12
每当您需要在拼接的字符串(或基本数学运算)中使用过滤器时,应该将其用括号包裹起来。例如: {{ ('http://' ~ app.request.host) | url_encode }}

1
非常有用,谢谢。我需要连接变量以作为翻译键使用。 - afilina

9

您可以像这样使用~{{ foo ~ 'inline string' ~ bar.fieldName }}

但是您也可以创建自己的concat函数,像在您的问题中那样使用它:
{{ concat('http://', app.request.host) }}

src/AppBundle/Twig/AppExtension.php中:

<?php

namespace AppBundle\Twig;

class AppExtension extends \Twig_Extension
{
    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('concat', [$this, 'concat'], ['is_safe' => ['html']]),
        ];
    }

    public function concat()
    {
        return implode('', func_get_args())
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'app_extension';
    }
}

app/config/services.yml中:
services:
    app.twig_extension:
        class: AppBundle\Twig\AppExtension
        public: false
        tags:
            - { name: twig.extension }

6

在Symfony中,您可以使用以下内容来指定协议和主机:

{{ app.request.schemeAndHttpHost }}

尽管@alessandro1997给出了完美的连接答案,但我们还需要更深入地讨论。

5

快速回答(TL;DR)

  • Twig字符串连接也可以使用format()过滤器来完成

详细回答

背景

  • Twig 2.x
  • 字符串构建和连接

问题

  • 场景:DeveloperGailSim希望在Twig中进行字符串连接
    • 本主题中的其他答案已经涉及了连字符
    • 本答案重点介绍更具表现力的format过滤器

解决方案

  • 另一种方法是使用format过滤器
  • format过滤器的工作方式类似于其他编程语言中的sprintf函数
  • 对于更复杂的字符串,format过滤器可能比~运算符更不繁琐

示例

  • 示例00 字符串拼接

      {{ "%s%s%s!"|format('alpha','bravo','charlie') }}
    --- 结果 --
    alphabravocharlie!

示例01

  • 示例01 带有插入文本的字符串拼接

      {{ "The %s in %s falls mainly on the %s!"|format('alpha','bravo','charlie') }}
    --- 结果 --
    The alpha in bravo falls mainly on the charlie!

示例02

  • 示例02 数字格式化的字符串拼接

  • 与其他语言中的sprintf语法相同

      {{ "The %04d in %04d falls mainly on the %s!"|format(2,3,'tree') }}
    --- 结果 --
    The 0002 in 0003 falls mainly on the tree!

另请参阅


3
为了混合字符串、变量和翻译,我只需按以下方式操作:
    {% set add_link = '
    <a class="btn btn-xs btn-icon-only" 
       title="' ~ 'string.to_be_translated'|trans ~ '" 
       href="' ~ path('acme_myBundle_link',{'link':link.id})  ~ '">
    </a>
    ' %}

尽管一切都混杂在一起,但它运行得非常顺畅。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接