
動態存取 Twig 變數名稱
在 Twig 中存取具有動態名稱的變數可能是一個挑戰。考慮以下場景:
1 2 3 4 5 6 7 8 | <p>placeholder1
placeholder2
placeholderx
</p>
<pre class = "brush:php;toolbar:false" >{% for invoices as invoice %}
need to display here the placeholder followed by the invoice id number
{{ placeholedr1 }}
|
登入後複製
使用上下文數組存取變數
您可以使用括號表示法存取_context 數組中的變數值,而不是使用屬性函數:
1 | {{ _context[ 'placeholder' ~ id] }}
|
登入後複製
這個選項更簡潔,可以說更清晰。
嚴格變數檢查
當環境選項中 strict_variables 設定為 true 時,您可能會遇到不存在變數的錯誤。要處理此問題,請使用預設過濾器:
1 2 3 | {{ _context[ 'placeholder' ~ id]| default }}
{{ attribute(_context, 'placeholder' ~ id)| default }}
|
登入後複製
檢查變數是否存在
要在存取變數之前檢查變數是否存在,請使用定義的檢定:
1 | {% if _context[ 'placeholder' ~ id] is defined %} ... {% endif %}
|
登入後複製
使用預設過濾器的預設值
使用|default:
1 2 3 | {{ _context[ 'placeholder' ~ id]| default (null) }}
{{ attribute(_context, 'placeholder' ~ id)| default ( 'Default value' ) }}
|
登入後複製
提供預設值,以防變數不存在
以上是如何動態存取 Twig 變數名?的詳細內容。更多資訊請關注PHP中文網其他相關文章!