简体   繁体   English

如何连接树枝中的字符串

[英]How to concatenate strings in twig

Anyone knows how to concatenate strings in twig?任何人都知道如何在树枝中连接字符串? I want to do something like:我想做类似的事情:

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

This should work fine:这应该可以正常工作:

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

To add a filter - like 'trans' - in the same tag use在同一个标​​签中添加一个过滤器——比如“trans”——使用

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

As Adam Elsodaney points out , you can also use string interpolation , this does require double quoted strings:正如Adam Elsodaney 指出的那样,您还可以使用字符串插值,这确实需要双引号字符串:

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

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

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

The operator you are looking for is Tilde (~), like Alessandro said, and here it is in the documentation:您正在寻找的运算符是波浪号 (~),就像亚历山德罗所说的,它在文档中:

~: Converts all operands into strings and concatenates them. ~:将所有操作数转换为字符串并连接起来。 {{ "Hello " ~ name ~ "!" {{“你好”~名字~“!” }} would return (assuming name is 'John') Hello John!. }} 会返回(假设名字是'John')Hello John!。 http://twig.sensiolabs.org/doc/templates.html#other-operators http://twig.sensiolabs.org/doc/templates.html#other-operators

And here is an example somewhere else in the docs :这是文档中其他地方的一个示例:

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

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

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

In this case, where you want to output plain text and a variable, you could do it like this:在这种情况下,你想输出纯文本和变量,你可以这样做:

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

If you want to concatenate some variables, alessandro1997's solution would be much better.如果你想连接一些变量,alessandro1997 的解决方案会好得多。

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

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

Whenever you need to use a filter with a concatenated string (or a basic math operation) you should wrap it with ()'s.每当您需要使用带有连接字符串(或基本数学运算)的过滤器时,您应该用 () 将其包裹起来。 Eg.:例如。:

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

In Symfony you can use this for protocol and host:在 Symfony 中,您可以将其用于协议和主机:

{{ app.request.schemeAndHttpHost }}

Though @alessandro1997 gave a perfect answer about concatenation.尽管@alessandro1997 给出了关于串联的完美答案。

You can use ~ like {{ foo ~ 'inline string' ~ bar.fieldName }}你可以使用~ like {{ foo ~ 'inline string' ~ bar.fieldName }}

But you can also create your own concat function to use it like in your question:但是您也可以创建自己的concat函数来像在您的问题中一样使用它:
{{ concat('http://', app.request.host) }} : {{ concat('http://', app.request.host) }} :

In src/AppBundle/Twig/AppExtension.phpsrc/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';
    }
}

In app/config/services.yml :app/config/services.yml

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

Quick Answer (TL;DR)快速回答 (TL;DR)

  • Twig string concatenation may also be done with the format() filter Twig 字符串连接也可以使用format()过滤器完成

Detailed Answer详细解答

Context语境

  • Twig 2.x树枝 2.x
  • String building and concatenation字符串构建和连接

Problem问题

  • Scenario: DeveloperGailSim wishes to do string concatenation in Twig场景: DeveloperGailSim 希望在 Twig 中进行字符串连接
    • Other answers in this thread already address the concat operator此线程中的其他答案已经解决了 concat 运算符
    • This answer focuses on the format filter which is more expressive此答案侧重于更具表现力的format过滤器

Solution解决方案

  • Alternative approach is to use the format filter另一种方法是使用format过滤器
  • The format filter works like the sprintf function in other programming languages format过滤器的工作方式类似于其他编程语言中的sprintf函数
  • The format filter may be less cumbersome than the ~ operator for more complex strings对于更复杂的字符串, format过滤器可能没有 ~ 操作符那么麻烦

Example00示例00

  • example00 string concat bare example00 字符串连接裸露

    \n\n{{ "%s%s%s!"|format('alpha','bravo','charlie') }} {{ "%s%s%s!"|format('alpha','bravo','charlie') }}\n\n--- result -- - - 结果  - \n\nalphabravocharlie!阿尔法布拉沃查理!\n\n

Example01示例01

  • example01 string concat with intervening text带有插入文本的 example01 字符串连接

    \n\n{{ "The %s in %s falls mainly on the %s!"|format('alpha','bravo','charlie') }} {{ "%s 中的 %s 主要落在 %s 上!"|format('alpha','bravo','charlie') }}\n\n--- result -- - - 结果  - \n\nThe alpha in bravo falls mainly on the charlie! bravo 中的 alpha 主要落在了查理身上!\n\n

Example02示例02

  • example02 string concat with numeric formatting带有数字格式的 example02 字符串连接
  • follows the same syntax as sprintf in other languages遵循与其他语言中的sprintf相同的语法

    \n\n{{ "The %04d in %04d falls mainly on the %s!"|format(2,3,'tree') }} {{ "%04d 中的 %04d 主要落在 %s!"|format(2,3,'tree') }}\n\n--- result -- - - 结果  - \n\nThe 0002 in 0003 falls mainly on the tree! 0003中的0002主要落在树上!\n\n

See also也可以看看

To mix strings, variables and translations I simply do the following:要混合字符串、变量和翻译,我只需执行以下操作:

    {% 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>
    ' %}

Despite everything being mixed up, it works like a charm.尽管一切都被混淆了,但它的作用就像一个魅力。

"{{ ... }}" 分隔符也可以在字符串中使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM