I am trying to dynamically assign variables in Twig inside a loop. For example, this is the JSON being passed into the template:
[{
"name": "firstName",
"value": "Adam",
},
{
"name": "Lastname",
"value": "Human",
}]
It's worth noting, I do not have the ability to modify this JSON formatting, as it's coming from a third party, so I need to solve this problem on the template side.
I want to loop through this json and create variables for each object, like so:
{% for item in json %}
{% set {{item.name}} = item.value %}
{% endfor %}
The challenge is Twig is assumes I'm assigning a value to a literal, when I want to assign the value to a evaluated variable name. This way I can just reference each item in the array like {{firstName}} and get back "Adam" in the template.
I've tried a number of different ways to force Twig to dynamically create a variable array, such as:
{% set (item.name) = item.value %}
and
{% set options = {} %}
{% for item in json %}
{% set options[item.name] = item.value %}
{% endfor %}
With no luck.
Any ideas on dynamically creating variables? This is straight forward in most programming languages, so I'm struggling to understand how this is handled in a template engine like Twig.