使用 twig 变量动态调用导入的宏子函数 [英] Using twig variable to dynamically call an imported macro sub-function

查看:20
本文介绍了使用 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-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

这篇关于使用 twig 变量动态调用导入的宏子函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆