[英]Twig: Print the value of a variable where the variable name is String
我有一個名為var1
的變量,其值value1
為字符串。 如何打印變量var1
的值,其中var1
是作為字符串獲得的?
讓
{{ set container = 'var1' }}
變量container
的值是動態的。 根據container
的價值,我需要打印它的價值; 在這種情況下,我需要打印'value1'。
我正在尋找這樣的東西
{{ attribute(this, container) }}
/ * <=這不會因為this
沒有在枝條定義* /
事實證明我錯了。
您可以使用包含傳遞給模板的所有變量的_context
變量。
試試{{ dump(_context) }}
您可以創建一個傳遞此上下文的函數,並使用數組鍵來訪問該值。
這個枝條功能應該工作正常:
public function getAttribute($context, $key)
{
if (!array_key_exists($key, $context)) {
return '';
}
return $context[$key];
}
變量傳遞title=foo
,另一個變量傳遞refTitle=title
,這應該輸出“foo”。
{{ attribute(_context, refTitle) }}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.