无法访问 TWIG 中 stdClass 的属性



我用谷歌搜索了一下,似乎 TWIG 的创建者真的坚持我在这里做的事情,这对我来说是 VIEW 的纯粹工作,模板根本不应该照顾的东西?!

我知道如果没有一些自定义的 TWIg 过滤器,我就无法迭代 stdClass 的对象,所以我现在破解了它,但是如果我不能动态访问属性,这个 TWIG 的东西真的不是很有用。

    $fixedModuleNames = array('time', 'date', 'weather'); //since TWIG doesn't iterate over objects by default, this is my solution, don't feel like adding a bunch of twigfilters just for this.
    $fixedModules = json_decode($entity->getFixedModules());
    /*
    Here's what fixedModules look like (although here not JSON but array, before encoded to json, I like to create my JSONs this way in PHP)
    $fixedModules["time"] = array(
        'show'          => true,
        'left'          => 10,
        'top'           => 10,
        'width'         => 100,
        'height'        => 200,
        'fontColor'     => '#000000',
        'fontSize'      => 40,
        'fontFamily'    => 'Arial',
        'borderColor'   => '',
        'borderRounding'=> 0,
        'bgColor'       => ''
    );
    */

这是我正在尝试做的...

                {% for item in fixedModuleNames %}
                <TR>
                    <TD><input type="number" id="left_{{ item }}" value="{{ fixedModules[item].left }}" class="LayoutModuleEditField" /></TD>

所以这条线失败了

{{ fixedModules[item].left }}

一定有办法解决这个问题,因为我正在做的事情非常例行公事?

啊,这也许是首选的方法吗?

{{ attribute(fixedModules, item).left }}

如果你的属性函数有效,那就使用它。

然而,考虑固定模块[item].left。 您要求 twig 找出该项目是一个变量,而 left 是一个常量。 至少可以说,任何系统都很难做到。

我会使用类似的东西:

{% for moduleName, module in fixedModules %} {# Time, Date, Weather module #}
    {% for itemName,itemValue in module %} {# Process each attribute in the module #}
        ...

如果你想迭代一个对象,那么只需实现数组迭代器接口。 通常很简单。

item不是

键,而是数组的一个元素。因此,您可以通过以下方式访问您的属性:

{% for item in fixedModuleNames %}
  left = {{ item.left }}
{% enfor %}

如果您确实想改用密钥,请执行以下操作:

{% for key, item in fixedModuleNames %}
  left = {{ fixedModuleNames[key].left }}
{% enfor %}

希望这有帮助。

最新更新