Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig Dynamic Variable Assignment

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.

like image 306
AdamPat Avatar asked Jul 04 '26 15:07

AdamPat


1 Answers

If the values are actually iterateable and not a single json string you can put them in an array like:

{% set values = [] %}
{% for item in json %}
    {% set values = values|merge({(item.name): item.value}) %}
{% endfor %}

Then you can use values.firstName.

If it is a json string and thus can't be looped through like this. You need to write a basic string parser in twig. I've written something similar like that last week in this answer however. Its a very bad idea in general as it fails on so many occasions.

like image 145
Jenne Avatar answered Jul 07 '26 05:07

Jenne