sto*_*fln 427 syntax templating string-concatenation twig
任何人都知道如何连接树枝中的字符串?我想做的事情如下:
{{ concat('http://', app.request.host) }}
Run Code Online (Sandbox Code Playgroud)
Ale*_*tis 830
这应该工作正常:
{{ 'http://' ~ app.request.host }}
Run Code Online (Sandbox Code Playgroud)
要添加过滤器 - 比如'trans' - 在同一个标签中使用
{{ ('http://' ~ app.request.host) | trans }}
Run Code Online (Sandbox Code Playgroud)
正如Adam Elsodaney指出的那样,你也可以使用字符串插值,这需要双引号字符串:
{{ "http://#{app.request.host}" }}
Run Code Online (Sandbox Code Playgroud)
Ada*_*ney 87
Twig中一个鲜为人知的特性是字符串插值:
{{ "http://#{app.request.host}" }}
Run Code Online (Sandbox Code Playgroud)
Nab*_*imi 24
您正在寻找的运营商是Tilde(〜),就像亚历山德罗所说的那样,在这里它是在文档中:
〜:将所有操作数转换为字符串并连接它们.{{"Hello"~name~"!" 会返回(假设名字是'John')你好约翰!- http://twig.sensiolabs.org/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 #}
Run Code Online (Sandbox Code Playgroud)
alg*_*imo 22
在这种情况下,您想要输出纯文本和变量,您可以这样做:
http://{{ app.request.host }}
Run Code Online (Sandbox Code Playgroud)
如果你想连接一些变量,alessandro1997的解决方案会好得多.
Sim*_*amp 13
{{ ['foo', 'bar'|capitalize]|join }}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这可以使用过滤器和函数,而无需set在单独的行上使用.
lso*_*uza 11
每当你需要使用带有连接字符串的过滤器(或基本的数学运算)时,你应该用()包装它.例如.:
{{ ('http://' ~ app.request.host) | url_encode }}
在Symfony中,您可以将它用于协议和主机:
{{ app.request.schemeAndHttpHost }}
Run Code Online (Sandbox Code Playgroud)
虽然@ alessandro1997给出了关于连接的完美答案.
您可以使用~像{{ 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';
}
}
Run Code Online (Sandbox Code Playgroud)
在app/config/services.yml:
services:
app.twig_extension:
class: AppBundle\Twig\AppExtension
public: false
tags:
- { name: twig.extension }
Run Code Online (Sandbox Code Playgroud)
format()过滤器完成 Twig 字符串连接format更具表现力的过滤器format过滤器format过滤器的工作方式类似于sprintf在其他编程语言功能format对于更复杂的字符串,过滤器可能没有 ~ 操作符那么麻烦example00 字符串连接裸露
{{ "%s%s%s!"|format('alpha','bravo','charlie') }}
- - 结果 -
阿尔法布拉沃查理!
带有插入文本的 example01 字符串连接
{{ "%s 中的 %s 主要落在 %s 上!"|format('alpha','bravo','charlie') }}
- - 结果 -
bravo 中的 alpha 主要落在了查理身上!
遵循与sprintf其他语言相同的语法
{{ "%04d 中的 %04d 主要落在 %s!"|format(2,3,'tree') }}
- - 结果 -
0003中的0002主要落在树上!