有人知道如何在树枝中连接字符串吗?我想做类似的事情:
{{ concat('http://', app.request.host) }}
这应该可以正常工作:
{{ 'http://' ~ app.request.host }}
要在同一个标签中添加过滤器 - 例如“trans” - 请使用
{{ ('http://' ~ app.request.host) | trans }}
作为 Adam Elsodaney points out,您也可以使用 string interpolation,这确实需要双引号字符串:
{{ "http://#{app.request.host}" }}
您正在寻找的运算符是波浪号 (~),就像 Alessandro 所说的那样,它在文档中:
~:将所有操作数转换为字符串并将它们连接起来。 {{“你好”~名字~“!” }} 会返回(假设名字是 'John')Hello John!。 – http://twig.sensiolabs.org/doc/templates.html#other-operators
这是一个示例 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 #}
在这种情况下,您想要输出纯文本和变量,您可以这样做:
http://{{ app.request.host }}
如果你想连接一些变量,alessandro1997 的解决方案会好很多。
{{ ['foo', 'bar'|capitalize]|join }}
如您所见,这适用于过滤器和函数,而无需在单独的行上使用 set
。
每当您需要使用带有串联字符串(或基本数学运算)的过滤器时,您应该用 () 将其包装起来。例如。:
{{ ('http://' ~ app.request.host) | url_encode }}
您可以像 {{ 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 }
在 Symfony 中,您可以将其用于协议和主机:
{{ app.request.schemeAndHttpHost }}
尽管@alessandro1997 给出了关于连接的完美答案。
快速回答 (TL;DR)
Twig 字符串连接也可以使用 format() 过滤器完成
详细解答
语境
树枝 2.x
字符串构建和连接
问题
场景:DeveloperGailSim 希望在 Twig 中进行字符串连接 此线程中的其他答案已经解决了 concat 运算符 此答案侧重于更具表现力的格式过滤器
该线程中的其他答案已经解决了 concat 运算符
这个答案侧重于更具表现力的格式过滤器
解决方案
另一种方法是使用格式过滤器
格式过滤器的工作方式类似于其他编程语言中的 sprintf 函数
对于更复杂的字符串,格式过滤器可能不如 ~ 运算符那么麻烦
示例00
example00 string concat bare {{ "%s%s%s!"|format('alpha','bravo','charlie') }} --- 结果 -- alphabravocharlie!
Example01
example01 string concat with intervening text {{ "The %s in %s主要落在%s上!"|format('alpha','bravo','charlie') }} --- result -- the alpha in bravo主要落在查理身上!
Example02
example02 带有数字格式的字符串连接
遵循与其他语言中的 sprintf 相同的语法 {{ "%04d 中的 %04d 主要落在 %s 上!"|format(2,3,'tree') }} --- 结果 -- 0003 中的 0002 落在主要是在树上!
也可以看看
http://twig.sensiolabs.org/doc/2.x/filters/format.html
https://stackoverflow.com/tags/printf/info
要混合字符串、变量和翻译,我只需执行以下操作:
{% 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>
' %}
尽管一切都混在一起,但它就像一个魅力。
"{{ ... }}" 分隔符也可以在字符串中使用:
"http://{{ app.request.host }}"
{% set foo = 'http://' ~ app.request.host %}
。然后你可以这样做:{{ foo | trans }}
。{{ form_open('admin/files/?path='~file_path|urlencode)|raw }}
不需要额外的变量。