I'm trying to use a twig variable to access attributes of another twig variable which was not working until I found the "attributes" function. Works well except in the cases where I need to access nested attributes. It doesn't work when the variable containing the attribute is actually an object + attribute. For example:
{{ attribute(object1, variable) }}
where variable = name, works just fine.
{{ attribute(object1, variable) }}
where variable = object2.name, doesn't work.
However, a hard coded test of {{ object1.object2.name }}
does work.
Here's how I got to this point...I have a yaml config file that gets parsed by the controller and passes it to twig in an array named 'config'. It contains parameters to define what gets displayed by the twig template.
fields:
- name: company.name
label: 'ODM'
indexView: true
recodrdView: true
- name: location
label: 'Location'
indexView: true
recordView: true
Additionally, an array of objects (entities) gets passed to the template for rendering.
The above "fields.name" is the name of the entity property. I iterate over the array of entities and then iterate over the config.fields array to determine what to display. Here's the twig code:
{% for data in datum %}
<tr>
{% for field in config.fields %}
{% if field.indexView %}
<td>{{ attribute(data, field.name }}</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
I get the error:
Neither the property "company.name" nor one of the methods "company.name()", "getcompany.name()"/"iscompany.name()"/"hascompany.name()" or "__call()" exist and have public access in class "App\Entity\Odm".
I suppose I could split up the field.name string with a '.' delimiter and then make the necessary number of calls to attribute, but I'm really hoping there's a more eloquent solution. I've also tried _context['data.' ~ field.name] - no luck there either.
Any ideas?