Ad

How To Append A Variable Inside Another Vaiable Name In Liquid Html

- 1 answer

Here is the code:

{% for i in (0..5) %}
  {% assign product = recommendations.top_related_products_{{i}}.products[0].title %}
  {{ product }}
{% endfor %}

This code throws the error Liquid error: Cannot read property '0' of null

I have 6 arrays under recommendation like top_related_products_0...5.

How do I print the title variable which is inside the top_related_products_0..5?

Ad

Answer

Create a string containing the variable name, then use square bracket notation to access it.

For example:

{% for i in (0..5) %}
  {% capture related_products %}top_related_products_{{i}}{% endcapture %}
  {{ recommendations[related_products].products.first.title }}
{% endfor %}
Ad
source: stackoverflow.com
Ad