【发布时间】:2011-12-03 23:48:18
【问题描述】:
有人知道如何在 twig 中连接字符串吗?我想做类似的事情:
{{ concat('http://', app.request.host) }}
【问题讨论】:
标签: syntax twig string-concatenation templating
有人知道如何在 twig 中连接字符串吗?我想做类似的事情:
{{ concat('http://', app.request.host) }}
【问题讨论】:
标签: syntax twig string-concatenation templating
这应该可以正常工作:
{{ 'http://' ~ app.request.host }}
要在同一个标签中添加过滤器——比如“trans”——使用
{{ ('http://' ~ app.request.host) | trans }}
作为Adam Elsodaney points out,你也可以使用string interpolation,这需要双引号字符串:
{{ "http://#{app.request.host}" }}
【讨论】:
{% set foo = 'http://' ~ app.request.host %}。然后你可以这样做:{{ foo | trans }}.
{{ form_open('admin/files/?path='~file_path|urlencode)|raw }} 不需要额外的变量。
在这种情况下,您想要输出纯文本和变量,您可以这样做:
http://{{ app.request.host }}
如果你想连接一些变量,alessandro1997 的解决方案会好很多。
【讨论】:
{{ ['foo', 'bar'|capitalize]|join }}
正如您所见,这适用于过滤器和函数,而无需在单独的行上使用 set。
【讨论】:
在 Symfony 中,您可以将其用于协议和主机:
{{ app.request.schemeAndHttpHost }}
虽然@alessandro1997 给出了关于串联的完美答案。
【讨论】:
当您需要使用带有串联字符串(或基本数学运算)的过滤器时,您应该使用 () 将其包装起来。例如:
{{ ('http://' ~ app.request.host) | url_encode }}
【讨论】:
要混合字符串、变量和翻译,我只需执行以下操作:
{% 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>
' %}
尽管一切都搞混了,但它的作用就像一个魅力。
【讨论】:
您要查找的运算符是波浪号 (~),就像 Alessandro 所说的那样,它在文档中:
~:将所有操作数转换为字符串并将它们连接起来。 {{ “你好 " ~ name ~ "!" }} 会返回(假设名字是 'John')你好 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 #}
【讨论】:
Twig 中还有一个鲜为人知的功能是string interpolation:
{{ "http://#{app.request.host}" }}
【讨论】:
“{{ ... }}”分隔符也可以在字符串中使用:
"http://{{ app.request.host }}"
【讨论】:
你可以像{{ 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 }
【讨论】:
format() 过滤器完成format 过滤器format 过滤器format 过滤器的工作方式类似于其他编程语言中的 sprintf 函数format 过滤器可能不如 ~ 运算符那么麻烦example00 string concat bare
{{ "%s%s%s!"|format('alpha','bravo','charlie') }} - - 结果 - 阿尔法布拉沃查利!example01 字符串与中间文本连接
{{ "%s 中的 %s 主要落在 %s 上!"|format('alpha','bravo','charlie') }} - - 结果 - Bravo中的阿尔法主要落在查理身上!遵循与其他语言中的sprintf 相同的语法
【讨论】: