2014-07-11 101 views
8

我在樹枝一些變量,如Symfony2的 - 如何訪問動態變量名在樹枝

placeholder1 
placeholder2 
placeholderx 

打電話給他們,我通過對象「發票」的陣列

{% for invoices as invoice %} 
    need to display here the placeholder followed by the invoice id number 
    {{ placeholedr1 }} 

任何循環理念?謝謝。

+0

你在哪裏定義佔位符1 - x?他們是全球可訪問的每個發票都有自己的佔位符嗎? – KhorneHoly

+0

我將它們定義在控制器中並將它們傳遞給樹枝模板。 –

+0

你能告訴我你定義和傳遞它們的代碼嗎?然後,我應該能夠幫助你:) – KhorneHoly

回答

19

我有同樣的問題 - 並使用此第一答案和一些其他的研究發現後{{ attribute(_context, 'placeholder'~invoice.id) }}應該工作(_context是按名稱包含所有對象的全球範圍內的對象)

0

我發現解決方案:

attribute(_context, 'placeholder'~invoice.id) 
2

我對這個問題的解決方案:

創建佔位符(x)的數組。像:

# Options 
$placeholders = array(
    'placeholder1' => 'A', 
    'placeholder2' => 'B', 
    'placeholder3' => 'C', 
); 

# Send to View ID invoice 
$id_placeholder = 2; 

發送兩個變量的觀點和你的模板調用:

{{ placeholders["placeholder" ~ id_placeholder ] }} 

本刊 「B」。

我希望這對你有所幫助。

2

除了使用attribute function,你可以與常規支架符號以及訪問_context數組的值:

{{ _context['placeholder' ~ id] }} 

我會親自用這一個,因爲它是更簡潔,在我看來更清晰。

如果environment optionstrict_variables設置爲true,你也應該使用default過濾器:

{{ _context['placeholder' ~ id]|default }} 

{{ attribute(_context, 'placeholder' ~ id)|default }} 

否則,如果變量不存在,你會得到一個Twig_Error_Runtime例外。例如,如果您有變量foobar但嘗試輸出變量baz(不存在),則會通過消息Key "baz" for array with keys "foo, bar" does not exist獲得該例外。

一個更詳細的方式來檢查一個變量的存在是使用defined test

{% if _context['placeholder' ~ id] is defined %} ... {% endif %} 

隨着default濾波器也可以提供一個默認值,例如null或字符串:

{{ _context['placeholder' ~ id]|default(null) }} 

{{ attribute(_context, 'placeholder' ~ id)|default('Default value') }} 

如果省略默認值(即您使用|default代替|default(somevalue)),默認值將是一個空字符串。

strict_variables默認爲false,但我更願意將其設置爲true以避免由於例如由於使用本文引起的意外問題。錯別字。

+0

訪問它是有道理的,而且imo更具可讀性。謝謝 – billynoah