无法访问TWIG中stdClass的属性

时间:2013-12-18 15:40:28

标签: php symfony object twig stdclass

我已经google了一下,似乎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 }}

必须有办法解决这个问题,因为我正在做的事情很常见吗?

3 个答案:

答案 0 :(得分:0)

啊,这可能是首选方式吗?

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

答案 1 :(得分:0)

如果您的属性功能有效,请使用它。

然而请考虑fixedModules [item] .left。您要求twig确定该项是变量,而left是常量。至少可以说任何系统都难以做到。

我会使用类似的东西:

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

如果要迭代对象,则只需实现数组迭代器接口。通常很简单。

答案 2 :(得分:0)

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

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

如果您真的想要使用密钥,请执行以下操作:

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

希望这有帮助。

相关问题