使用 twig 变量动态调用导入的宏子函数变量、动态、子函数、twig

由网友(有你们陪着我)分享简介:我正在尝试是否使用变量来调用特定的宏名称.I am attempting if use a variable to call a specific macro name.我有一个正在导入的宏文件I have a macros file that is being imported{% import 'form-...

我正在尝试是否使用变量来调用特定的宏名称.

I am attempting if use a variable to call a specific macro name.

我有一个正在导入的宏文件

I have a macros file that is being imported

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

现在该文件中有所有表单元素宏:text、textarea、select、radio 等.

Now in that file there are all the form element macros: text, textarea, select, radio etc.

我有一个传入的数组变量,其中包含一个元素:

I have an array variable that gets passed in that has an elements in it:

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

{{ elements }}

我试图做的是从宏中生成这些元素.当按名称调用时,它们工作得很好:

what im trying to do is generate those elements from the macros. they work just fine when called by name:

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

但是我想做的是这样的:

However what i want to do is something like this:

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

我已经尝试了以下所有导致相同的错误:

I have tried the following all resulting in the same error:

{{ 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) }}

不幸的是,这会引发以下错误:

This unfortunately throws the following error:

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

任何关于解决方案或更好使用模式的帮助或建议都会非常有帮助.

Any help or advice on a solution or a better schema to use would be very helpful.

推荐答案

我只是认为其他人可能想要这个问题的答案,正如 fabpot 提供的那样:

I just thought other people may want the answer to this, as provide by 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:

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

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

-fabpot

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

阅读全文

相关推荐

最新文章