2012-12-04 29 views
8

我在嘗試使用變量來調用特定的宏名稱。使用twig變量來動態調用導入的宏子函數

我正在導入

{% import 'form-elements.html.twig' as forms %} 

現在,在該文件中有所有表單元件宏的宏文件:文本,文本區域,選擇,無線電等

我有一個數組變量通過其中有一個元素:

$elements = array(
    array(
     'type'=>'text, 
     'value'=>'some value', 
     'atts'=>null, 
    ), 
    array(
     'type'=>'text, 
     'value'=>'some other value', 
     'atts'=>null, 
    ), 
); 

{{ elements }} 

什麼即時嘗試做的是從宏中生成這些元素。

{{ forms.text(element.0.name,element.0.value,element.0.atts) }} 

但是我想要做的是這樣的:

{% for element in elements %} 
{{ forms[element.type](element.name,element.value,element.atts) }} 
{% endfor %} 

我曾嘗試以下所有導致同樣的錯誤:

{{ forms["'"..element.type.."'"](element.name,element.value,element.atts) }} 
{{ forms.(element.type)(element.name,element.value,element.atts) }} 
{{ forms.{element.type}(element.name,element.value,element.atts) }} 
時的名字叫他們的工作就好了

這不幸引發以下錯誤:

Fatal error: Uncaught exception 'LogicException' with message 'Attribute "value" does not exist for Node "Twig_Node_Expression_GetAttr".' in Twig\Environment.php on line 541 

任何關於解決方案或更好的架構的幫助或建議都會非常有用。

回答

15

我只是想,其他人可能想這個問題的答案,如fabpot提供:

This is indeed something that is not supported: calling a macro with a dynamic name (I have added a proper exception to be clearer about the issue).

If you really want to do that, you can do so with the following code:

{{ attribute(forms, element.type, [element.name,element.value,element.atts]) }}

-fabpot

https://github.com/twigphp/Twig/issues/922#issuecomment-11133299

+1

在枝條2,這已不再是從我瞭解的解決方案:(,爲安全原因屬性無法訪問模板。 – notacouch