Liquid Guide: Common code samples for advanced use cases

  • Updated
Description

This article contains some examples of Liquid code that is commonly used when building out more advanced use cases.

 

Examples

Empty arrays must be initialized before data can be added to them

{% assign new_array = nil | concat: nil %}

 

Special characters must be escaped before additional filtering

{% assign collection = product.collection | unescape %}{% if collection contains '>' %} {{ collection | split: '>' | first}} {% else %} {{collection}} {% endif %}

 

.size can be used to check whether a returned result is empty

{% if b_data[0].size < 1%} {% abort %} {% endif %}

 

Dynamically generate future date for 2 weeks from the campaign send time 

{% assign current_time = now %} pulls in the current unix timestamp at the time the campaign runs

{% assign two_weeks = 1209600 %} this is two weeks worth of seconds

{% assign expiration = current_time | plus: two_weeks | date: "%a, %d %b, %Y" %} takes the current timestamp, adds 2 weeks of seconds, and formats to a human-readable date

{{expiration}}      

 

De-duplicating arrays to combine lookup results      

{% assign abandoned = array1 %}

{% for p in array2 %}

{% assign new_prod = true %} this variable is used to mark array items before adding them to final array

{% for c in array1 %}        

{% if p.product.category.path == c.product.category.path %}

{% assign new_prod = false %}

{% break %} causes the loop to stop and move onto the next item

{% endif %}

{% endfor %}

{% if new_prod %} if the item is marked as true for new_prod, then they are added to final array 

{% assign abandoned = abandoned | concat: p %}

{% endif %}

{% endfor %}

 

De-duplicating single array based on an attribute

{% assign prods = nil | concat: nil %} initialize new empty array to store final results

{% for p in lookup_prods %}

{% assign new_prod = true %}

 {% for pp in prods %}

{% if p.field == pp.field %}

{% assign new_prod = false %}

{% break %}

{% endif %}

{% endfor %}

{% if new_prod %}

{% assign prods = prods | concat: p %}

{% endif %}

{% endfor %}

 

Referencing two separate arrays in one dynamic grid

1st array:  {{final_prods}} contains products added to cart 

- make this the Custom Source in Content of the grid

 

Assign ‘idx’ as your item index variable

 

 

2nd array: {{parsed_items}} contains qty added for each product 

Logic to match the 2 arrays goes in the Column’s Setup block:

{% for pp in parsed_items %} 

{% assign p_id = pp.product_id | downcase %} 

{% assign f_id = final_prods[idx].product_id %}

{% if p_id == f_id %} matching based on product_id

{% assign item_quantity = pp.quantity %}

{% assign item_product_id = pp.product_id %}

{% endif %}{% endfor %}

Referencing the two arrays 

in the campaign: 

Description: {{item_quantity}}

Quantity: {{final_prods[idk].name}}

 

Additional Resources