有人知道如何连接树枝中的字符串吗?我想做的事情是:

{{ concat('http://', app.request.host) }}

当前回答

这应该可以正常工作:

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

在相同的标签中添加一个过滤器,如“trans”

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

正如Adam Elsodaney指出的,你也可以使用字符串插值,这确实需要双引号字符串:

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

其他回答

你要找的操作符是Tilde(~),就像Alessandro说的,这里是在文档中:

~:将所有操作数转换为字符串并连接。{{“你好 " ~名字~ "!"}}将返回(假设名字是“John”)你好,John!。——http://twig.sensiolabs.org/doc/templates.html其他运营商

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

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

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

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

你可以使用~,比如{{foo ~ 'inline string' ~ bar。字段名}}

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

在src / AppBundle -树枝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 }

Twig还有一个鲜为人知的特性是字符串插值:

{{ "http://#{app.request.host}" }}
{{ ['foo', 'bar'|capitalize]|join }}

正如你所看到的,这与过滤器和函数一起工作,而不需要在单独的行上使用set。

在这种情况下,你想输出纯文本和一个变量,你可以这样做:

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

如果你想连接一些变量,alessandro1997的解决方案会更好。