La vida vista con mis manos.

Shopify and the ‘WITH’ variable param

By on 22 julio, 2016 in Coding with 0 Comments

When creating a shopify theme, sometime you will have a liquid snipped that may change according to the template where you include it, but is not good to repeat the code if you need a simple variation.

In those cases we can use the param WITH, which is no more than variables that you can send via


{% include %}

Lets see this example:

File: social-links.liquid

<a href="facebook.com" {% if blank %} target="_BLANK" {% endif %}>Faceboo</a>
<a href="twitter.com" {% if blank %} target="_BLANK" {% endif %}>Twitter</a>
<a href="linkedin.com" {% if blank %} target="_BLANK" {% endif %}>LinkedI</a>

File:  product.liquid


{% include 'social-links' with blank: true %}

So, the output will be:

<a href="facebook.com" target="_BLANK">Faceboo</a>
<a href="twitter.com" target="_BLANK">Twitter</a>
<a href="linkedin.com" target="_BLANK">LinkedI</a>

If you for some reason, want to open in the same window your social profile, just include the file without WITH:


{% include 'social-links' %}

output:

<a href="facebook.com">Faceboo</a>
<a href="twitter.com">Twitter</a>
<a href="linkedin.com">LinkedI</a>

Another good example when passing variables:

The with parameter assigns a value to a variable inside a snippet that shares the same name as the snippet. Whilst this might sound confusing at first, have a quick look at this example:


<ul>
{% for product in collection-product-list %}
<li><a href= "{{ product.url}}">{{ product.title}}</a>
{% endfor %}
<ul>

And:


{% assign products = collections.all.products %}
{% include ‘collection-product-list’ with products %}

Here, i am assigning the collection. all.products to a Liquid variable. Here i called it products but can be named as you like.

Next we move onto the include tag and reference the snippet without the .liquid extension and follow it with with products. The with parameter assigns a value to a variable inside a snippet that shares the same name as the snippet. Whilst this might sound confusing at first, have a quick look at the example above which has the following line in:


{% for product in collection-product-list %}

Effectively what is happening is that the variable products is referenced within the snippet by collection-product-list. As such, our snippet will now function with any product collection we pass in using the with parameter.

Tags:

About the Author

About the Author: Ing. Sistemas ... Programador, @Koombea RockStar | Soy un Zombie | Amo el Café | Ciclomontañista | Nunca Duermo | #PizzaBrain .

Subscribe

If you enjoyed this article, subscribe now to receive more just like it.

Top