Mechanic
📣 Shopify REST Deprecation
  • ⛩️Introduction
  • 🤓Hire a Mechanic developer
  • 💯status.mechanic.dev
  • 📣Shopify is deprecating the REST API
  • 🙋"I need something custom!"
  • 🧑‍💻"I need help with my custom task!"
  • 🤖"I need help with my AI-written task!"
  • Resources
    • ⬇️Install Mechanic
    • 🧑‍💻Task library
      • Contributing
      • Requesting
    • 🚀Slack community
    • 🤝Partner directory
    • 🧠Tutorials
      • Video walkthroughs
        • Auto-tag orders by originating staff member
        • Maintain a tag for orders processed today
        • Auto-tag orders with their tracking numbers
        • Sync inventory for shared SKUs
        • Auto-tag products when their SKU(s) change
        • Auto-publish new products
        • Email a report of customers who haven't ordered in X days
        • Upgrading a Mechanic task: Adding a time delay
        • Email the customer when tracking numbers are added to their order
        • Adding an optional time delay to your Mechanic task
        • Delete all orders
        • Send an email when a specific product is shipped
        • Send recurring reminders about unpaid orders
        • Send an email when a product's price goes below its cost
        • Auto-tag customers by sales channel
        • Creating products in bulk
      • Creating a Mechanic webhook
      • Practicing writing tasks
      • Triggering tasks from a contact form
      • Creating scheduled CSV feeds
      • Fetching data from a shared Google sheet
    • 🏆Converting tasks from Shopify REST to GraphQL
      • Conversion: Single resource lookups
      • Conversion: Resource loops to paginated queries
      • Conversion: Connections from a resource
      • Conversion: Metafield lookups from a resource
      • Conversion: Resource lookups in task option fields
  • Core Concepts
    • Events
      • Topics
      • Parent and child events
    • Tasks
      • Subscriptions
      • Code
        • Environment variables
        • Action objects
        • Error objects
        • Log objects
      • Options
        • Custom validation
      • Previews
        • Defining preview events
        • Stub data
      • Shopify API version
      • Advanced settings
        • Documentation
        • JavaScript
        • Perform action runs in sequence
      • Import and export
      • User Form
    • Actions
      • Cache
      • Echo
      • Email
      • Event
      • Files
      • Flow
      • FTP
      • Google Drive
      • Google Sheets
      • HTTP
      • Integrations
        • Report Toaster
      • Shopify
      • File generators
        • Base64
        • PDF
        • Plaintext
        • URL
        • ZIP
    • Runs
      • Scheduling
      • Concurrency
      • Ordering
      • Retries
    • Interacting with Shopify
      • Responding to events
        • Reconciling missing events
      • Reading data
        • ⚠️Liquid objects
        • 🏆GraphQL in Liquid
        • Bulk operations
        • The Shopify action
      • Writing data
      • Shopify admin action links
      • API rate limit
      • API versions
  • Platform
    • 🔆Policies
      • Data
      • Plans
      • Pricing
      • Privacy
    • Cache
      • Cache endpoints
    • Email
      • Receiving email
      • Custom email addresses
      • DMARC
      • Email templates
    • Error handling
    • Events
      • Event topics
      • Event filters
    • GraphQL
      • Basics
        • Shopify Admin API GraphiQL explorer
        • Queries
        • Mutations
        • Pagination
      • Bulk operations
    • Integrations
      • Appstle Subscriptions
      • Google Drive and Google Sheets
      • Judge.me
      • Locksmith
      • Report Toaster
      • Shopify Flow
      • Run links
    • Liquid
      • Basics
        • Syntax
        • Data types
        • Variables
        • Comments
        • Filters
        • Operators
        • Control flow
          • Condition
          • Iteration
        • Whitespace
      • Liquid console
      • Mechanic filters
        • Deprecated filters
      • Mechanic keyword literals
        • array
        • hash
        • newline
      • Mechanic objects
        • Action object
        • Cache object
        • Event object
        • Options object
        • Task object
        • ⚠️Shopify REST Admin API
          • 🚫Article object
          • 🚫Blog object
          • 🚫Collection object
          • 🚫Customer object
          • 🚫Discount code object
          • 🚫Dispute object
          • 🚫Draft order object
          • 🚫Fulfillment object
          • 🚫Fulfillment order object
          • 🚫Fulfillment event object
          • 🚫Gift card object
          • 🚫Inventory item object
          • 🚫Inventory level object
          • 🚫Line item object
          • 🚫Location object
          • 🚫Metafields
            • Metafield object
            • Metafield representation object
            • Metafield collection object
          • 🚫Order object
          • 🚫Order risk object
          • 🚫Price rule object
          • 🚫Product object
          • 🚫Product image object
          • 🚫Refund object
          • 🚫Shipping zone object
          • 🚫Shop object
          • 🚫Theme object
          • 🚫Theme asset object
          • 🚫Transaction object
          • 🚫Variant object
      • Mechanic tags
        • liquid
        • action
        • assign
        • error
        • log
      • Mechanic code snippets
    • Shopify
      • Custom authentication
      • "Read all orders"
    • Webhooks
  • Techniques
    • Preventing action loops
    • Writing a high-quality task
    • Tagging Shopify resources
    • Debouncing events
    • Responding to action results
    • Working with external APIs
      • JSON Web Signatures
      • AWS request signatures
    • Finding a resource ID
    • Migrating templates from Shopify to Mechanic
    • Securing Mechanic webhooks
    • Monitoring Mechanic
  • FAQ
    • The app isn't loading. What do I do?
    • How do I stop a large batch of runs?
    • A Shopify event is missing. Where is it?
    • Does Mechanic have an affiliate program?
    • Can non-owners install Mechanic?
    • Can I replace Shopify's order emails with Mechanic?
    • Can I manually set Shopify permissions for Mechanic?
    • Does my theme need to be updated for Mechanic?
    • Do you have a plan for development stores?
    • Why don't I see any events in my task's activity?
    • Can I read data back from my webhook submission?
    • My task added a tag, but now the tag is missing – why?
    • How do I add an unsubscribe link to my emails?
    • How do I send images with my emails?
    • Can I re-send order confirmation emails with Mechanic?
    • Why am I seeing a different price than on the app store?
    • Do you have a Partner-friendly plan?
    • Why are my tasks delayed or not running?
    • My task is failing because of a permissions problem. Why?
    • How do I preview email attachments?
    • Can I query external APIs?
    • Why can't I access the Shopify API during preview mode?
    • How do marketing preferences work with Mechanic?
    • Can I send data to Google Sheets?
    • What's possible with timeline comments?
    • I'm getting a "query param length is too long" error when using GraphQL.
    • Can my Mechanic concurrency limit be raised?
    • What IP address does Mechanic use?
    • Can Mechanic read or manage customer subscriptions?
    • Why is everything harder now?
    • Can task content be translated into multiple languages?
    • Can I add a time delay to my task?
    • Can I add another store to my existing Mechanic subscription?
    • How can I reduce memory usage of my task?
    • How do I connect PayPal to Shopify with Mechanic?
    • How do I add a Shopify access scope to my task?
    • Can I have my Mechanic data retained for more (or less) than 15 days?
Powered by GitBook

Important Updates

  • 📣 Shopify REST Deprecation
On this page
  • Data filters
  • browser
  • csv, parse_csv
  • date, parse_date
  • gzip, gunzip
  • graphql_arguments
  • json, parse_json
  • jsonl, parse_jsonl
  • parse_xml
  • shopify
  • Shopify Data filters
  • String filters
  • e164
  • match
  • hmac_sha512
  • rsa_sha256, rsa_sha512
  • scan
  • sha512
  • unindent
  • Shopify String filters
  • Math filters
  • currency
  • Shopify Math filters
  • Array filters
  • in_groups
  • in_groups_of
  • index_by
  • push
  • sample
  • slice
  • sort_naturally
  • unshift
  • Shopify Array filters
  • Hash filters
  • compact
  • except
  • keys
  • slice
  • values

Was this helpful?

Edit on GitHub
Export as PDF
  1. Platform
  2. Liquid

Mechanic filters

This page defines all of the Liquid filters that are available in Mechanic Liquid. Mechanic supports many of our own filters, as well as an array of filters drawn from Shopify Liquid.

Note that not all Shopify Liquid filters are supported by Mechanic. If a filter is supported by Shopify but it's not included on this page, it's not available in Mechanic Liquid.

Liquid filters should not be confused with event filters, which are used to conditionally ignore incoming events.

Data filters

browser

This filter converts a browser user agent string into an object that represents the browser itself. Data from Browserscope is used to match user agents.

{% assign browser = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) GSA/79.0.259819395 Mobile/16G77 Safari/604.1" | browser %}

{{ browser }}

name: {{ browser.name }}

version: {{ browser.version }}
major version: {{ browser.version.major }}
minor version: {{ browser.version.minor }}

os: {{ browser.os }}
os name: {{ browser.os.name }}
os version: {{ browser.os.version }}
os major version: {{ browser.os.version.major }}
os minor version: {{ browser.os.version.minor }}

device: {{ browser.device }}
device name: {{ browser.device.name }}
device brand: {{ browser.device.brand }}
device model: {{ browser.device.model }}
Google 79.0.259819395

name: Google

version: 79.0.259819395<br>major version: 79<br>minor version: 0

os: iOS 12.4<br>os name: iOS<br>os version: 12.4<br>os major version: 12<br>os minor version: 4

device: iPhone<br>device name: iPhone<br>device brand: Apple<br>device model: iPhone

csv, parse_csv

Supports converting a two-dimensional array to a CSV string, and back again.

Arguments

  • delimiter (optional): A single character that separates the fields in the CSV. Defaults to a comma.

  • include_bom (optional): A boolean value that, when set to true, includes a Byte Order Mark (BOM) at the beginning of the CSV string to enhance compatibility with Microsoft Excel. Defaults to false.

{{ data | csv }}
{{ data | csv: ";" }}
{{ data | csv: include_bom: true }}
{{ data | csv: ";", include_bom: true }}
{% if event.preview %}
  {% capture shop_json %}
    {
      "products": [
        {
          "id": 1234567890,
          "title": "Short sleeve t-shirt"
        }
      ],
      "name": "My Test Shop",
      "customer_email": "shop@example.com"
    }
  {% endcapture %}

  {% assign shop = shop_json | parse_json %}
{% endif %}

{% assign rows = array %}

{% assign header = array %}
{% assign header[0] = "Product ID" %}
{% assign header[1] = "Product Title" %}

{% assign rows[0] = header %}

{% for product in shop.products %}
  {% assign row = array %}
  {% assign row[0] = product.id %}
  {% assign row[1] = product.title %}

  {% assign rows[rows.size] = row %}
{% endfor %}

{%- comment -%}
  Generate CSV with custom delimiter and include BOM for Excel compatibility
{%- endcomment -%}
{% assign csv = rows | csv: ";", include_bom: true %}

{% action "email" %}
  {
    "to": {{ options.email_recipient__email_required | json }},
    "subject": {{ "Product ID export for " | append: shop.name | json }},
    "body": "Please see attached. :)",
    "reply_to": {{ shop.customer_email | json }},
    "from_display_name": {{ shop.name | json }},
    "attachments": {
      "export.csv": {{ csv | json }}
    }
  }
{% endaction %}

{% action "echo" csv %}

{%- capture csv_string_default_delimiter -%}
Order Name,Order ID,Order Date
#1234,1234567890,2021/03/23
#1235,1234567891,2021/03/24
{%- endcapture %}

{%- capture csv_string_custom_delimiter -%}
Order Name;Order ID;Order Date
#1234;1234567890;2021/03/23
#1235;1234567891;2021/03/24
{%- endcapture %}

{% comment %}
  Parse CSV with default delimiter (comma)
{% endcomment %}
{% assign orders_with_default_delimiter = csv_string_default_delimiter | parse_csv: headers: true %}
{% action "echo" orders_with_default_delimiter %}

{% comment %}
  Parse CSV with custom delimiter (semicolon)
{% endcomment %}
{% assign orders_with_custom_delimiter = csv_string_custom_delimiter | parse_csv: headers: true, delimiter: ";" %}
{% action "echo" orders_with_custom_delimiter %}

{% comment %}
  Parse CSV without headers, default delimiter
{% endcomment %}
{% assign csv_rows_default_delimiter = csv_string_default_delimiter | parse_csv %}

{% assign orders_without_headers_default_delimiter = array %}
{% for row in csv_rows_default_delimiter %}
  {% if forloop.first %}
    {% continue %}
  {% endif %}

  {% assign order = hash %}
  {% assign order["name"] = row[0] %}
  {% assign order["id"] = row[1] | times: 1 %}
  {% assign order["date"] = row[2] %}

  {% assign orders_without_headers_default_delimiter[orders_without_headers_default_delimiter.size] = order %}
{% endfor %}

{% action "echo" orders_without_headers_default_delimiter %}

{% comment %}
  Parse CSV without headers, custom delimiter
{% endcomment %}
{% assign csv_rows_custom_delimiter = csv_string_custom_delimiter | parse_csv: delimiter: ";" %}

{% assign orders_without_headers_custom_delimiter = array %}
{% for row in csv_rows_custom_delimiter %}
  {% if forloop.first %}
    {% continue %}
  {% endif %}

  {% assign order = hash %}
  {% assign order["name"] = row[0] %}
  {% assign order["id"] = row[1] | times: 1 %}
  {% assign order["date"] = row[2] %}

  {% assign orders_without_headers_custom_delimiter[orders_without_headers_custom_delimiter.size] = order %}
{% endfor %}

{% action "echo" orders_without_headers_custom_delimiter %}

date, parse_date

Mechanic's date filter is based on Shopify's date filter, and has several important extensions.

Quick reference
{{ "now"
    | date: [format,]

      [tz: "America/Chicago",]

      [beginning_of_year: true,]
      [end_of_year: true,]

      [beginning_of_quarter: true,]
      [end_of_quarter: true,]

      [beginning_of_month: true,]
      [end_of_month: true,]

      [beginning_of_week: "monday",]
      [end_of_week: "sunday",]

      [beginning_of_day: true,]
      [end_of_day: true,]
      [middle_of_day: true,]

      [advance: "1 day 10 minutes",]
}}

Format

Date formats may be given per Ruby's strftime. For an interactive format-building tool, see strfti.me.

Unlike Shopify Liquid, Mechanic's date filter does not require a format argument. If one is not given, Mechanic defaults to formatting the date per ISO8601.

{{ "2000-01-01" | date: "%Y-%m-%d %H:%M %z" }}
=> "2000-01-01 00:00 -0600"

{{ "2000-01-01" | date }}
=> "2000-01-01T00:00:00-06:00"

{{ "2000-01-01" | date: tz: "UTC" }}
=> "2000-01-01T06:00:00Z"

Using the current time

This filter accepts the special value "now". This may optionally be combined with a single date calculation, as in "now + 5 days" or "now - 5 weeks". For specifics on date calculation, see notes below for the advance option.

Additional options

The date filter also accepts these following options, evaluated in the following order:

  1. tz — A timezone name from the TZ database

    • If given, the resulting time string will be in the specified timezone.

    • If this option is not provided, the time is assumed to be in the store's local timezone, as configured at the Shopify level.

    • All date calculations are performed with respect to the current timezone, with consideration for DST and other calendar variances.

  2. beginning_of_year: true or end_of_year: true

  3. beginning_of_quarter: true or end_of_quarter: true

  4. beginning_of_month: true or end_of_month: true

  5. beginning_of_week: weekday or end_of_month: weekday

    • weekday must be a string naming the first day of the week for the intended usage, e.g. "sunday" or "monday"

  6. beginning_of_day: true or middle_of_day: true or end_of_day: true

  7. advance: "1 year 6 months"

    • Supports any combination of years, months, weeks, days, hours, minutes, seconds

    • Supports positive and negative values

    • Durations are calculated in the order given, left to right

    • Seconds, minutes, and hours are all implemented as constant intervals

    • Days, weeks, months, and years are all variable-length, appropriate for the current time in the current timezone (see tz). For example, {{ "2023-01-31" | date: "%F", advance: "1 year 1 month" }} returns 2024-02-29.

    • Commas and signs may be used for clarity. Pluralization is optional. All of the examples below are equivalent:

      • {{ "now" | date: advance: "-3 hours, +2 minutes, -1 second" }}

      • {{ "now" | date: advance: "-3 hours, 2 minutes, -1 second" }}

      • {{ "now" | date: advance: "-3 hour 2 minute -1 second" }}

      • {{ "now" | date: advance: "-3 hours 2 minutes -1 seconds" }}

Parsing dates

Use parse_date to parse a date string, when its exact format is known. This filter is useful for strings that contain an ambiguous date value, like "01/01/01".

Under the hood, parse_date uses ActiveSupport::TimeZone#strptime, and inherits its behavior with regard to missing upper components.

This filter returns an ISO8601 string, representing the parsed date value in the store's local timezone. If the supplied date string cannot be parsed successfully, the filter will return nil.

{{ "01-01-20" | parse_date: "%m-%d-%y" }}
=> "2020-01-01T00:00:00+11:00"

{{ "01-01-20" | parse_date: "%m-%d-%y" | date: "%Y-%m-%d" }}
=> "2020-01-01"

{{ "ab-cd-ef" | parse_date: "%m-%d-%y" }}
=> nil

gzip, gunzip

These filters allow you to compress and decompress strings, using gzip compression.

In general, all strings passing through Mechanic must be UTF-8, and must ultimately be valid when represented as JSON. However, because gzip'd content may not be UTF-8, and because it may be important to preserve the original encoding, the gunzip filter supports a force_utf8: false option. Use this when you're certain the original encoding must be preserved, if you ultimately intend to pass along the string in a JSON-friendly representation. (For example, you might gunzip a value, and then use the base64 filter to represent it safely within JSON.)

{{ "testing" | gzip | gunzip }}
=> "testing"

{{ "hello world" | gzip | base64 }}
=> "H4sIABwbfl8AA8tIzcnJVyjPL8pJAQCFEUoNCwAAAA=="

{{ "H4sIANAafl8AA8tIzcnJVyjPL8pJAQCFEUoNCwAAAA==" | decode_base64: force_utf8: false | gunzip }}
=> "hello world"

{% assign base64_non_utf8_string = "H4sIACP1fV8AAyvPSCxRSMlPLVbILFHITU3MUyjJV0hKVXjUMKc4J7/8UcNcewAYP+lTIwAAAA==" %}
{{ base64_non_utf8_string | decode_base64: force_utf8: false | gunzip: force_utf8: false }}
=> (a string that is not UTF-8, and cannot be exported to JSON as-is)

{% assign base64_non_utf8_string = "H4sIACP1fV8AAyvPSCxRSMlPLVbILFHITU3MUyjJV0hKVXjUMKc4J7/8UcNcewAYP+lTIwAAAA==" %}
{{ base64_non_utf8_string | decode_base64: force_utf8: false | gunzip }}
=> "what does it mean to be “slow”?"

graphql_arguments

Useful for preparing key-value pairs of GraphQL query or mutation arguments.

Across the documentation and task library, you'll frequently see json used for serializing argument values. Users have reported some rare cases where this filter is insufficient, and where graphql_arguments does the trick instead.

graphql_arguments is typically used for rendering GraphQL values into the final GraphQL query string itself. Instead, consider extracting your values as GraphQL variables. This approach can result in more reusable query code.

To try this using a Shopify action, use the GraphQL with variables syntax.

To try this using the shopify filter, use the variables argument.

{% assign inputs = hash %}
{% assign inputs["a_string"] = "yep this is a string" %}
{% assign inputs["a_more_complex_type"] = hash %}
{% assign inputs["a_more_complex_type"]["id"] = "gid://something/Or?other" %}
{% assign inputs["an_array"] = array %}
{% assign inputs["an_array"][0] = 1 %}
{% assign inputs["an_array"][1] = 2 %}

{% action "shopify" %}
  mutation {
    anExample({{ inputs | graphql_arguments }}) {
      result
    }
  }
{% endaction %}

This results in a GraphQL Shopify action containing the following GraphQL:

mutation {
  anExample(
    a_string: "yep this is a string"
    a_more_complex_type: { id: "gid://something/Or?other" }
    an_array: [1, 2]
  ) {
    result
  }
}

For a more complex example, see Set product or variant metafields values in bulk from the task library.

json, parse_json

Allows converting objects to their JSON representations, and parsing that JSON into hashes.

{% assign order_as_json = order | json %}
{% assign plain_order = order_as_json | parse_json %}

The parse_json filter raises an error when invalid JSON. To ignore parse errors, and to return null when an error is encountered, add silent: true to the filter's options:

{% assign should_be_nil = "{{" | parse_json: silent: true %}

jsonl, parse_jsonl

Allows for rendering an iterable object (i.e. an array) as a series of JSON lines, separated by simple newlines.

{{ shop.customers | jsonl }}

The parse_jsonl filter can be used to parse a series of JSON strings, each on their own line, into an array of hashes. Useful when preparing stub data for bulk operations.

{% capture jsonl_string %}
  {"id":"gid://shopify/Customer/12345","email":"foo@bar.baz"}
  {"id":"gid://shopify/Customer/67890","email":"bar@baz.qux"}
{% endcapture %}

{% assign json_objects = jsonl_string | parse_jsonl %}

{{ json_objects | map: "email" | join: ", " }}

The parse_jsonl filter raises an error when invalid JSONL is received.

parse_xml

Use this filter to parse an XML string. (Under the hood, this filter calls Hash::from_xml.) Useful for processing output from third-party APIs, either by responding to "http" actions, or by parsing content from inbound webhooks.

{% capture xml_string %}
<foo>
  <bar>baz</bar>
  <bar>
    <qux>quux</qux>
  </bar>
</foo>
{% endcapture %}

{% assign xml = xml_string | parse_xml %}

{{ xml | json }}
{"foo":{"bar":["baz",{"qux":"quux"}]}}

shopify

This filter accepts a GraphQL query string, sends it to Shopify, and returns the full response – including "data" and "errors".

Use Shopify's GraphiQL query builder to quickly and precisely assemble your queries.

{% capture query %}
  query {
    shop {
      primaryDomain {
        host
      }
    }
  }
{% endcapture %}

{% assign result = query | shopify %}

{% log result %}
{
  "log": {
    "data": {
      "shop": {
        "primaryDomain": {
          "host": "example.com",
        },
      }
    },
    "extensions": {
      "cost": {
        "requestedQueryCost": 2,
        "actualQueryCost": 2,
        "throttleStatus": {
          "maximumAvailable": 1000.0,
          "currentlyAvailable": 998,
          "restoreRate": 50.0
        }
      }
    }
  }
}

GraphQL variables

This filter also supports GraphQL variables, via an optional named argument called variables.

Variables can be a useful part of making queries reusable within a task, or for working around Shopify's 50,000 character limit for GraphQL queries.

{% capture query %}
  query ProductQuery($id: ID!) {
    product(id: $id) {
      title
    }
  }
{% endcapture %}

{% assign variables = hash %}
{% assign variables["id"] = product_id %}

{% assign result = query | shopify: variables: variables %}

{% log result %}


{% comment %}
  Alternate style, avoiding the `variables: variables` construction:
{% endcomment %}

{% assign query_options = hash %}
{% assign query_options["variables"] = hash %}
{% assign query_options["variables"]["id"] = product_id %}

{% assign result = query | shopify: query_options %}

Shopify Data filters

In addition to our own filters, Mechanic supports the following data filter from Shopify Liquid:

  • default


String filters

e164

This filter accepts a phone number – country code is required! – and outputs it in standard E.164 format. If the number does not appear valid, the filter returns nil.

{{ "1 (312) 456-7890" | e164 }}
=> "13124567890"

{{ "+43 670 1234567890" | e164 }}
=> "436701234567890"

{{ "000" | e164 | json }}
=> "null"

match

Use this filter to match a string with a Ruby-compatible regular expression pattern (see Regexp).

This filter returns the entire matched string (i.e. MatchData#to_s). Use the "captures" or "named_captures" lookups to receive an array or hash of captures, respectively (i.e. MatchData#captures, MatchData#named_captures).

This filter only returns the first match found. To find all available matches in a string, use scan.

{{ "It's a lovely day!" | match: "(?<=a ).*(?= day)" }}
=> "lovely"

{% assign match = "It's a lovely day!" | match: "a (bucolic|lovely) day" %}
{{ match.captures }}
=> ["lovely"]

{% assign match = "It's a lovely day!" | match: "a (?<adjective>bucolic|lovely) day" %}
{{ match.named_captures }}
=> {"adjective" => "lovely"}

{% assign match = "It's a lovely day!" | match: "a (?i:LOVELY) day" %}
{{ match }}
=> "a lovely day"

hmac_sha512

Works like hmac_sha256 from Shopify Liquid, but uses SHA-512 instead.

rsa_sha256, rsa_sha512

Accepts string input, given an RSA PEM key string as a filter option.

This filter is useful for generating JSON Web Signatures!

{{ input | rsa_sha256: private_key_pem }}
{{ input | rsa_sha256: private_key_pem, binary: true | base64_encode }}
{{ input | rsa_sha512: private_key_pem }}
{{ input | rsa_sha512: private_key_pem, binary: true | base64_encode }}

scan

Use this filter to find all available matches in a string, using a Ruby-compatible regular expression pattern (see Regexp).

This filter returns an array of matches, consisting of each matched string (i.e. MatchData#to_s). Use the "captures" or "named_captures" lookups on individual matches to receive an array or hash of captures, respectively (i.e. MatchData#captures, MatchData#named_captures).

This filter returns an array of matches. To only find the first match, use match.

{{ "It's a lovely day!" | scan: "[\w']+" }}
=> ["It's", "a", "lovely", "day"]

{{ "It's a lovely day!" | scan: "(bucolic|lovely|day)" | map: "captures" }}
=> [["lovely"], ["day"]]

{{ "It's a lovely day!" | scan: "(?<punctuation>[[:punct:]])" | map: "named_captures" }}
=> [{"punctuation" => "'"}, {"punctuation" => "!"}]

sha512

Works like sha256 from Shopify Liquid, but uses SHA-512 instead.

unindent

Use this filter on strings to remove indentation from strings.

{% capture message %}
  Hello, friend!
  It's a mighty fine day!
{% endcapture %}

{{ message }}
{{ message | unindent }}
  Hello, friend!
  It's a mighty fine day!


Hello, friend!
It's a mighty fine day!

Shopify String filters

In addition to our own filters, Mechanic supports the following string filters from Shopify Liquid:

  • append

  • base64_decode

  • base64_encode

  • base64_url_safe_decode

  • base64_url_safe_encode

  • capitalize

  • downcase

  • escape

  • escape_once

  • handleize

  • hmac_sha1

  • hmac_sha256

  • lstrip

  • md5

  • newline_to_br

  • pluralize

  • prepend

  • remove

  • remove_first

  • remove_last

  • replace

  • replace_first

  • replace_last

  • rstrip

  • sha1

  • sha256

  • slice

  • split

  • strip

  • strip_html

  • strip_newlines

  • truncate

  • truncatewords

  • upcase

  • url_decode

  • url_encode


Math filters

currency

Formats a number (given as an integer, float, or string) as currency. Called with no arguments, this filter uses the store's primary currency and default locale.

A three-character ISO currency code may be specified as the first argument; currency support is drawn from the money project. The locale may be overridden as a named option; locale support is drawn from rails-i18n.

{{ "100000.0" | currency }}
{{ 100000.0 | currency: "EUR" }}
{{ 100000 | currency: "EUR", locale: "fr" }}
{{ 100000 | currency: locale: "fr" }}
$100,000.00
€100,000.00
€100 000,00
$100 000,00

Note that this filter does not automatically append the currency ISO code (e.g. it will not generate output resembling "€100,000.00 EUR"). To add the ISO code manually, use one of these examples:

{{ price | currency }} {{ shop.currency }}
{{ price | currency | append: " " | append: shop.currency }}

Shopify Math filters

In addition to our own filters, Mechanic supports the following math filters from Shopify Liquid:

  • abs

  • at_least

  • at_most

  • ceil

  • divided_by

  • floor

  • minus

  • modulo

  • plus

  • round

  • times


Array filters

in_groups

This filter is an implementation of Array#in_groups. It accepts an array, and an integer count, and – optionally – a "fill_with" option.

{{ "1,2,3" | split: "," | in_groups: 2 | json }}
[["1","2"],["3",null]]
{{ "1,2,3" | split: "," | in_groups: 2, fill_with: false | json }}
[["1","2"],["3"]]

in_groups_of

This filter is an implementation of Array#in_groups_of. It accepts an array, and an integer count, and – optionally – a "fill_with" option.

This filter is particularly useful when performing work in batches, by making it easy to split an array of potentially large size into smaller pieces of controlled size.

{{ "1,2,3,4,5" | split: "," | in_groups_of: 2 | json }}
[["1","2"],["3","4"],["5",null]]
{{ "1,2,3,4,5" | split: "," | in_groups_of: 2, fill_with: false | json }}
[["1","2"],["3","4"],["5"]]

index_by

This filter accepts the name of an object property or attribute, and returns a hash that whose values are every element in the array, keyed by every element's corresponding property or attribute.

{% capture variants_json %}
  [
    {
      "id": 12345,
      "sku": "ONE"
    },
    {
      "id": 67890,
      "sku": "TWO"
    }
  ]
{% endcapture %}

{% assign variants = variants_json | parse_json %}

{{ variants | index_by: "sku" | json }}
{
  "ONE": {
    "id": 12345,
    "sku": "ONE"
  },
  "TWO": {
    "id": 67890,
    "sku": "TWO"
  }
}

push

This filter appends any number of arguments onto the provided array, returning a new array, leaving the original unmodified.

{% assign count_to_three = "one,two,three" | split: "," %}

{% assign count_to_five = count_to_three | push: "four", "five" %}

{{ count_to_five | join: newline }}
one
two
three
four
five

sample

This filter can be used on any array. Used without any arguments, it returns a single random element from the array. Provide an integer argument to return another array of that size, containing a random subset of the input array.

{{ "1,2,3" | split: "," | sample }}
=> "2"

{{ "1,2,3" | split: "," | sample: 2 | join: "," }}
=> "3,1"

slice

When applied to an array, this filter accepts an integer offset, and an optional integer length (defaulting to 1). If the length is 1, it returns the single element found at that index of the input array. Otherwise, it returns a slice of the array, beginning at the provided index, having the provided length.

Negative offsets begin counting from the end of the array.

{{ "1,2,3,4,5" | split: "," | slice: 3 }}
=> "4"

{{ "1,2,3,4,5" | split: "," | slice: 3, 2 | join: "," }}
=> "4,5"

{{ "1,2,3,4,5" | split: "," | slice: -3, 2 | join: "," }}
=> "3,4"

sort_naturally

Sorts an array uses the human-friendly sort order defined by naturally. Accepts a single optional parameter, specifying an attribute to sort.

This filter complements Shopify Liquid's sort and sort_natural filters. Choose your sort filter intentionally: machine audiences are typically happier with "sort", and human audiences are typically happier with "sort_naturally".

{% assign set = "order #10.b,Order #10.a,Order #2.c,order #2.d" | split: "," %}

unsorted:
  {{ set | join: ", " }}
sort:
  {{ set | sort | join: ", " }}
sort_natural:
  {{ set | sort_natural | join: ", " }}
sort_naturally:
  {{ set | sort_naturally | join: ", " }}
unsorted:
  order #10.b, Order #10.a, Order #2.c, order #2.d
sort:
  Order #10.a, Order #2.c, order #10.b, order #2.d
sort_natural:
  Order #10.a, order #10.b, Order #2.c, order #2.d
sort_naturally:
  Order #2.c, Order #10.a, order #2.d, order #10.b

unshift

This filter prepends any number of arguments onto the provided array, returning a new array, leaving the original unmodified.

{% assign count_two_three = "two,three" | split: "," %}

{% assign count_to_three_and_start_at_zero = count_two_three | unshift: "zero", "one" %}

{{ count_to_three_and_start_at_zero | join: newline }}
zero
one
two
three

Shopify Array filters

In addition to our own filters, Mechanic supports the following array filters from Shopify Liquid:

  • compact

  • concat

  • first

  • join

  • last

  • map

  • reverse

  • size

  • sort

  • sort_natural

  • sum

  • uniq

  • where


Hash filters

compact

When applied to a hash, this filter returns a new hash which omits all keys having nil values.

{% assign foo = hash %}
{% assign foo["bar"] = "baz" %}
{% assign foo["qux"] = nil %}
{{ foo | json }}
{{ foo | compact | json }}
{"bar":"baz","qux":null}
{"bar":"baz"}

except

This filter accepts one or more string arguments, corresponding to keys that should be left out of the output. The filter returns a new hash, containing all the key/value pairs of the original hash except those keys named as arguments.

{% assign foo = hash %}
{% assign foo["bar"] = "bar" %}
{% assign foo["baz"] = "baz" %}
{% assign foo["qux"] = "qux" %}

{{ foo | except: "bar", "baz" | json }}
{"qux":"qux"}

keys

Returns an array of keys found in the supplied hash.

slice

When applied to a hash, the slice filter accepts one or more string arguments, corresponding to keys that the hash may contain. This filter will then return a new hash, containing only matching key/value pairs from the original hash.

{% assign foo = hash %}
{% assign foo["bar"] = "bar" %}
{% assign foo["baz"] = "baz" %}
{% assign foo["qux"] = "qux" %}

{{ foo | slice: "bar", "baz" | json }}
{"bar":"bar","baz":"baz"}

values

Returns an array of values found in the supplied hash.

PreviousLiquid consoleNextDeprecated filters

Last updated 4 months ago

Was this helpful?