skip to Main Content

I need to customize the shipping confirmation email. I want to use a tag to determine which of two text sections are included in the email. The problem is there is usually an array of tags. I can get section "A" like this…

{% for tag in tags %}
{% if tag == ‘a’ %}
A
{% endif %}
{% endfor %}

There is only a single ‘a’ tag in the array so I only get the "A" text once.

But I can’t figure out how to get the "B" text to appear just one time.

If I do this, it appears for every tag that does not == ‘a’…

{% for tag in tags %}
{% unless tag contains ‘a’ %}
B
{% endunless %}
{% endfor %}

Is there a way to get one instance of "B"?

2

Answers


  1. If you have many tags it can become tricky, but if it’s just two tags this is the general idea.

    {% assign a_not_found = true %}
    {% for tag in tags %}
      {% if tag == 'a' %}
        ...
        {% assign a_not_found = false %}
      {% endif %}
    {% endfor %}
    {% if a_not_found %}
      {... show b... }
    {% endif %}
    

    Otherwise

    {% if tags contains 'a' %}
    {...show a...%}
    {% else %}
    {...show b...%}
    {% endif %}
    
    Login or Signup to reply.
  2. You could repeat the same logic you did for A:

    {% for tag in tags %}
      {% if tag == 'a' %}
        A
      {% endif %}
      {% if tag == 'b' %}
        B
      {% endif %}
    {% endfor %}

    Alternatively you could do a switch/case statement, I’d prefer this approach because it’s easy to read, and if sometime in the future you would like to add another condition (tag), it would be easy and the code would still keep its elegance.

    {% for tag in tags %}
      {% case tag %}
        {% when 'a' %}
          A
        {% when 'b' %}
          B
        {% when 'c' %}
          C
      {% endcase %}
    {% endfor %}
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search