can't access property of stdClass in TWIG

2.8k Views Asked by At

I have googled around and it seems as though the creators of TWIG really insists that what I am doing here, which is to me a pure job for the VIEW, something that the template shouldn't take care of at all?!

I know I can't iterate over an object of stdClass without some custom TWIg filters, so I hacked that for now, but if I can't eve access properties dynamically this TWIG thing really isn't very useful at all.

    $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'       => ''
    );
    */

Here's what I am trying to do...

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

So this line fails

{{ fixedModules[item].left }}

There must be a way around this since what I am doing is very routine?

3

There are 3 best solutions below

0
On

Ah, is this perhaps the preferred way of doing it?

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

If your attribute function works then use it.

Consider however fixedModules[item].left. You are asking twig to figure out that item is a variable while left is a constant. Difficult for any system to do to say the least.

I would use something like:

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

If you want to iterate over an object then just implement the array iterator interface. Usually pretty simple.

0
On

item is not the key, but an element of your array. So you can access your attributes this way:

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

If you really want to use the key instead, do something like:

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

Hope this helps.