Shopify / liquid

Liquid markup language. Safe, customer facing template language for flexible web apps.
https://shopify.github.io/liquid/
MIT License
11.11k stars 1.39k forks source link

Printing out a variable, where part of the name of it is another variable? #771

Open randohinn opened 8 years ago

randohinn commented 8 years ago

I have a list of {% assign %} tags that go something like this:

{% assign blog_1_name = "blog 1" %}
{% assign blog_2_name = "blog 2" %}
{% assign blog_3_name = "blog 3" %}
{% assign blog_4_name = "blog 4" %}

And then I have another assign, called blog_count and set to 4. I would now like to loop over the blog_count and display the specific blog_X_name, where X is the current iteration. Tried something like this. Didn't work

{% for i in (1..postcount) %}
                <div class="col-xs-12 col-md-6 col-md-offset-3 blogpost-link">
                    <h2>{{ blog_..i.._name }}</h2>
                 </div>

{%endfor%}

Can this be done?

freakdesign commented 8 years ago

@randohinn You could consider something like this (assuming that postcount is set to 4):

{% assign blog_1_name = "blog 1" %}
{% assign blog_2_name = "blog 2" %}
{% assign blog_3_name = "blog 3" %}
{% assign blog_4_name = "blog 4" %}

{% for i in (1..postcount) %}
  {% assign varName = 'blog_%1_name' | replace:'%1',i %}
  <div class="col-xs-12 col-md-6 col-md-offset-3 blogpost-link">
    <h2>{{ [varName] }}</h2>
  </div>
{% endfor %}
randohinn commented 8 years ago

@freakdesign Nope, nothing prints out...

fw42 commented 8 years ago

Not a very nice solution, but what you can do is put your blog names into an array (for example by spliting a string like "blog 1|blog 2|blog 3") and then indexing into that array (like names[i]). Not sure if there's a nicer way, at least not unless you control the environment in which Liquid is used (but I guess this is in a Shopify theme).

Hope that helps.

randohinn commented 8 years ago

It's not a theme, so I have near-complete control over the environment. Building with gulp-liquify if that's to be considered a limitation.