【问题标题】:can't access property of stdClass in TWIG无法在 TWIG 中访问 stdClass 的属性
【发布时间】:2013-12-18 15:40:28
【问题描述】:

我在谷歌上搜索了一下,似乎 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 }}

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

【问题讨论】:

  • 记录一下:如果你将true 作为json_decode 的第二个参数传递,你会得到一个关联数组而不是\stdClass 实例。
  • 不错!然而,我似乎失去了每个部分的“名称”(上例中的“时间”)。有没有办法保存它?

标签: php symfony object twig stdclass


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果您的属性函数有效,请使用它。

    但请考虑 fixedModules[item].left。您要求 twig 找出 item 是一个变量,而 left 是一个常量。至少可以说任何系统都很难做到。

    我会使用类似的东西:

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

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

    【讨论】:

    • 我看不出我想要做什么与 PHP 中的任何关联数组有什么不同? $array["subName"]["property"]
    【解决方案3】:

    item 不是键,而是数组的一个元素。所以你可以通过这种方式访问​​你的属性:

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

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

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

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-17
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多