有人知道如何在Twig中连接字符串吗?我想做类似于:
{{ concat('http://', app.request.host) }}
有人知道如何在Twig中连接字符串吗?我想做类似于:
{{ concat('http://', app.request.host) }}
这应该能正常工作:
{{ 'http://' ~ app.request.host }}
要在同一标签中添加过滤器(如'trans'),请使用:
{{ ('http://' ~ app.request.host) | trans }}
正如Adam Elsodaney指出的那样,您还可以使用字符串插值,但需要使用双引号括起来:
{{ "http://#{app.request.host}" }}
还有一个鲜为人知的Twig功能是字符串插值:
{{ "http://#{app.request.host}" }}
你要找的运算符是波浪号(~),就像Alessandro所说的那样,在文档中可以找到:
~:将所有操作数转换为字符串并将它们连接起来。{{ "Hello " ~ name ~ "!" }} 将返回(假设name是'John')Hello John!。- http://twig.symfony.com/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 #}
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 }}
format()
过滤器来完成format
过滤器format
过滤器format
过滤器的工作方式类似于其他编程语言中的sprintf
函数format
过滤器可能比~运算符更不繁琐示例00 字符串拼接
{{ "%s%s%s!"|format('alpha','bravo','charlie') }}
--- 结果 --
alphabravocharlie!
示例01 带有插入文本的字符串拼接
{{ "The %s in %s falls mainly on the %s!"|format('alpha','bravo','charlie') }}
--- 结果 --
The alpha in bravo falls mainly on the charlie!
示例02 数字格式化的字符串拼接
与其他语言中的sprintf
语法相同
{{ "The %04d in %04d falls mainly on the %s!"|format(2,3,'tree') }}
--- 结果 --
The 0002 in 0003 falls mainly on the tree!
{% 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>
' %}
{% set foo = 'http://' ~ app.request.host %}
。然后你可以这样使用:{{ foo | trans }}
。 - Alessandro Desantis