2017-04-08 62 views
3

我需要能夠測試Twig中宏的存在並動態調用它。在Twig 2中測試宏的存在

這裏是我的嘗試:

{% macro test(value) %} 
    Value: {{ value }} 
{% endmacro %} 

{% import "_macros.html.twig" as macro %} 

{{ attribute(macro, 'test', ['foo']) }} 

但我得到這個錯誤:Accessing Twig_Template attributes is forbidden.

問候,

回答

2

由於枝條1.20.0,模板屬性不再可用出於安全原因,所以沒有原生的方式來正確地做到這一點。

您最終可以使用source函數來獲取宏的源文件並解析它以檢查宏是否存在,但這是一種容易繞過的醜陋黑客。

實施例:

main.twig

{% import 'macros.twig' as macros %} 

{% set sourceMacros = source(macros) %} 

foo {% if 'foo()' in sourceMacros %} exists {% else %} does not exist {% endif %} 

bar {% if 'bar()' in sourceMacros %} exists {% else %} does not exist {% endif %} 

macros.twig

{% macro foo() %} 
Hello, world! 
{% endmacro %} 

參見this example live

另一種方法WO要創建一個custom test來完成這項工作。

+0

謝謝你,我不知道'源'。如果你的宏有params,例如'{%macro foo(bar)%}',你必須更新''foo()''以便逐字匹配。 ''foo(bar)'或''{%macro foo(''。 – notacouch