有人知道如何连接树枝中的字符串吗?我想做的事情是:
{{ concat('http://', app.request.host) }}
有人知道如何连接树枝中的字符串吗?我想做的事情是:
{{ concat('http://', app.request.host) }}
当前回答
{{ ['foo', 'bar'|capitalize]|join }}
正如你所看到的,这与过滤器和函数一起工作,而不需要在单独的行上使用set。
其他回答
“{{…”-分隔符也可以在字符串中使用:
"http://{{ app.request.host }}"
在这种情况下,你想输出纯文本和一个变量,你可以这样做:
http://{{ app.request.host }}
如果你想连接一些变量,alessandro1997的解决方案会更好。
Twig还有一个鲜为人知的特性是字符串插值:
{{ "http://#{app.request.host}" }}
在Symfony中,您可以将此用于协议和主机:
{{ app.request.schemeAndHttpHost }}
尽管@alessandro1997给出了一个关于串联的完美答案。
你可以使用~,比如{{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 }