[英]Twig print available from string
如何在我的代碼php中在樹枝中打印可用的表單字符串
$data['fruits'] = array('apple', 'banana', 'orange');
$data['help_apple'] = 'This is help apple';
$data['help_banana'] = 'This is help for banana';
$data['help_orange'] = 'This is help for orange';
在樹枝模板中
{% for fruit in fruits %}
{{ "help_" ~ fruit }}
{% endfor %}
打印屏幕是help_apple,help_banana,help_orange如何打印我需要help_水果鍵的正確數據?
您需要將屬性函數與_context一起使用。 在twigfiddle.com上測試。 希望這可以幫助。
{% for fruit in fruits %}
{# Here is how you do it #}
{{ attribute(_context, 'help_'~ fruit) }}
{% endfor %}
_context
變量保存當前上下文中的所有變量。 除了使用attribute
函數之外 ,您還可以使用常規方括號表示法訪問_context
數組的值:
{% for fruit in fruits %}
{{ _context['help_' ~ fruit] }}
{% endfor %}
我個人將以這種方式進行操作,因為它更簡潔並且我認為更清晰。
訪問_context
數組的值時,可能要檢查未定義的變量。 我在回答以下問題時已經寫過: Symfony2-如何在twig中訪問動態變量名 。
您還問這樣的事情是否可能:
{% set attribute(context, 'help' ~ fruit, "value") %}
那不可能 如果要使用動態名稱設置變量,則需要創建一個Twig擴展名。 看看我對這個問題的回答: 如何使用動態變量設置變量名?
但是,就像提到的@ user9189147一樣,如果您創建一個新數組來保存幫助值,那會更容易,而且我認為更清晰。 然后,您無需創建擴展。
$data['fruits'] = ['apple', 'banana', 'orange'];
$data['help'] = [];
$data['help']['apple'] = 'This is help apple';
$data['help']['banana'] = 'This is help for banana';
$data['help']['orange'] = 'This is help for orange';
{% for fruit in fruits %}
{{ help[fruit] }}
{% endfor %}
然后,您可以使用merge
過濾器將新值設置為Twig中的幫助值(盡管我不知道您為什么要在Twig中這樣做):
{# Set single value #}
{% set help = help|merge({
banana: 'New help for banana',
}) %}
{# Or multiple values #}
{% set help = help|merge({
apple: 'An apple a day keeps the doctor away',
orange: 'Orange is the new black',
}) %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.