[英]How to concatenate strings in 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}" }}
您正在尋找的運算符是波浪號 (~),就像亞歷山德羅所說的,它在文檔中:
~:將所有操作數轉換為字符串並連接起來。 {{“你好”~名字~“!” }} 會返回(假設名字是'John')Hello 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 #}
在這種情況下,你想輸出純文本和變量,你可以這樣做:
http://{{ app.request.host }}
如果你想連接一些變量,alessandro1997 的解決方案會好得多。
{{ ['foo', 'bar'|capitalize]|join }}
正如您所看到的,這適用於過濾器和函數,而無需在單獨的行上使用set
。
每當您需要使用帶有連接字符串(或基本數學運算)的過濾器時,您應該用 () 將其包裹起來。 例如。:
{{ ('http://' ~ app.request.host) | url_encode }}
在 Symfony 中,您可以將其用於協議和主機:
{{ app.request.schemeAndHttpHost }}
盡管@alessandro1997 給出了關於串聯的完美答案。
你可以使用~
like {{ 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 字符串連接裸露
\n\n {{ "%s%s%s!"|format('alpha','bravo','charlie') }}\n\n - - 結果 - \n\n阿爾法布拉沃查理!\n\n
帶有插入文本的 example01 字符串連接
\n\n {{ "%s 中的 %s 主要落在 %s 上!"|format('alpha','bravo','charlie') }}\n\n - - 結果 - \n\n bravo 中的 alpha 主要落在了查理身上!\n\n
遵循與其他語言中的sprintf
相同的語法
\n\n {{ "%04d 中的 %04d 主要落在 %s!"|format(2,3,'tree') }}\n\n - - 結果 - \n\n 0003中的0002主要落在樹上!\n\n
要混合字符串、變量和翻譯,我只需執行以下操作:
{% 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 }}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.