Search code examples
shopifyliquidliquid-layout

Including Snippets and Templates with conditions in Liquid


I'm trying to include some snippets and templates on a product page based on the product type. However, liquid doens't seem to generate snippets conditionally.

An example of what I'm trying to achieve:

{% if product.type == 'shoes' %}
   {% include 'shoes-template' %}
{% else %}
   {% include 'other-template' %}
{% endif %}

Solution

  • If you have many product types, instead of using multiple if and else if, you can use an array and a contains. You can also verify if a template exist by performing a capture and looking for the string "Liquid error".

    {% assign types = "shoes, shirts, pants" | split:", " %}
    {% if types contains product.type %}
        {% assign snip = product.type | append:"-template" %}
    {% else %}
        {% assign snip = "other-template" %}
    {% endif %}
    
    {% capture snip_content %}{% include snip %}{% endcapture %}
    {% unless snip_content contains "Liquid error" %}
        {% include snip %}
    {% endunless %}