Ad

Liquid (Shopify) - Append String Is Empty

- 1 answer

In Shopify I am trying to build a string of the current tags in my shopify store.

If I am on the page:

mysite.com/collections/all/tag1+tagC+tag4

I need to be able to get the current tags as one full string without spaces:

tag1+tagC+tag4

My code is currently like so:

{% if current_tags %}
    {% assign current_filters = '' %}
    {% for tag in current_tags %}
      {% if forloop.last == false %}
        {{ current_filters | append: tag | handleize | append: '+'}}
      {% else %}
        {{ current_filters | append: tag | handleize}}
      {% endif%}
    {% endfor %}
{% endif %}

If I then output

{{current_filters}}

I get

tag1+ tagC+ tag4

Firstly how do I go about getting this string without the space after the plus sign? I have tried using | strip without luck and also putting my code within {%- -%}

Secondly when I then try and append that current_filters variable onto the end of another variable it is blank/empty

{% assign current_collection = collection.handle %}
{% assign base_url = shop.url | append: '/collections/' | append: current_collection | append: '/' | append: current_filters %}

Outputting base_url just returns

mysite.com/collections/all/

not

mysite.com/collections/all/tag1+tagC+tag4

Why is this working when I just use {{current_filters}} but not .. append: current_filters

Ad

Answer

I think you are confusing the basic syntax of liquid.

The {{ ... }} are used only for outputing data/content, no for assigning.

So when you say:

{{ current_filters | append: tag | handleize | append: '+' }} 
// Logic "" (empty value) "tag" (the tag) "+" (the string)

you output the empty value of current_filters but add to it the value of the tag and the +. But at the end you are not modifying the current_filters value at all. So at the end it will still be an empty string.

For assigning/modifying values you always use {% ... %}, so in your case you should modify the this code:

{{ current_filters | append: tag | handleize | append: '+'}} 

to this one:

{% assign current_filters = current_filters  | append: tag | handleize | append: '+' %}

In addition you have the join filter that will make all of the code above redundant.

You can just call {{ current_tags | join: '+' }} and you are ready.

Ad
source: stackoverflow.com
Ad