Creating a dynamic capture

I need some help with the code below. Within a template I’m creating multiple tables with the same design. So, what I’d like to do is create a number of captures dynamically, so I call on them later on in my code. What I’m going for is this:

{% assign categories = "name1;value1|name2;value2" | split:"|" %}

{% for category in categories %}

  {% assign parts = category | split:";" %}
  
{% capture table_name %}table_{{ parts[0] }}{% endcapture %}
{% capture result_value %}{{ parts[1] }}{% endcapture %}

{% capture [table_name] %}
{{ result_value }}
{% endcapture %}
{% endfor %}

{{ table_name1 }}

But this gives me an no value for {{table_name1}}, where I would suspect to see value1.

Am I doing something wrong?

Hi

When you are capturing a name of the variable, the variable cannot be between brackets. Please use assign for variables in brackets:

{% assign categories = "name1;value1|name2;value2" | split:"|" %}

{% for category in categories %}

  {% assign parts = category | split:";" %}

{% capture table_name %}table_{{ parts[0] }}{% endcapture %}
{% capture result_value %}{{ parts[1] }}{% endcapture %}

{% capture temp_table_name_value %}{{ result_value }}{% endcapture %}
{% assign [table_name] = temp_table_name_value %}

{% endfor %}

{{ table_name1 }}

Please let me know if this works for you.
Thanks

1 Like

Yeah that makes perfect sense, thanks so much!