August 09, 2022

Shopify Flow - Use assign, capture, and map in Liquid

In fields that allow Liquid in Flow, you can now make full use of the tags assign and capture to set variables. You can use the map filter to create an array of values from another array.

Assign allows you to do complex math and string manipulations to a single field or list. It also allows you to use the output of one set of tags in another tag. For example, you can generate a random number between 1 and 10 like this:

{% assign min = 1 %}
{% assign max = 10 %}
{% assign diff = max | minus: min %}
{% assign theRandomNumber = "now" | date: "%N" | modulo: diff | plus: min %}

Capture allows you to write complex logic and strings and then capture the output of a block of liquid to a variable. This means you can write functions for your liquid in one place and then use the variable in much simplified liquid.

{%- capture title -%}
{% if product.title contains “XYZ” -%}
Upcase title: {{ product.title | upcase }}
{%- else -%}
Downcase title: {{ product.title | downcase }}
{%- endif %}
{%- endcapture %}

{% comment %}Use title field{% endcomment %}

{{ title }}

Map allows you to easily create a list of values from a specific property of the items in a list. You can also combine this with assign to make a variable. For example, this outputs the titles for all the products in a collection, separated by a comma.

{%- assign product_titles = collection.products | map: 'title' -%}
{{ product_titles | join: ', ' }}

Learn more about Shopify Flow from the Shopify Help Center.