Search code examples
shopifyliquid

How to append tags in a forlop to an array in shopify liquid


I am trying to make an array which already has some tags.. I want to loop through each product in cart and add the tags to the array. The {{tag }} part is working but its not getting assigned to the array..

{% assign finalTaglist = "apples, oranges, peaches" | split: ", " %}
        
        {% for item in cart.items %}
          <p>
            {% for tag in item.product.tags %}
                {{tag}}
            
                {% assign finalTaglist = finalTaglist | concat: tag %}
            
            {% endfor%}
          </p>
        {% endfor%}
        
        <p>Final Tag List : {{finalTaglist}}</p>`

`


Solution

  • concat is used for joining arrays, but your code is trying to add a string to an array, hence why it doesn't work.

    Start with an empty string, and use append to add on to the string, not forgetting your separator. Once built, use split to create the array, then you can append to another array if required.

    Something along these lines (not tested, just winging it, but you get the idea..)

    {% assign finalTaglist = 'apples,oranges,peaches' | split: ',' %}
    
    {% assign newTagList = '' %}
    {% for item in cart.items %}
        {% for tag in item.product.tags %}
            {% assign newTagList = newTagList | append: ',' | append: tag %}
        {% endfor%}
    {% endfor%}
    
    {% assign newTagList = newTagList | remove_first: ',' | split: ',' %}
    
    {% assign joinedTagLists = finalTaglist | concat: newTagList %}