Homepage

Liquid - platformOS Liquid Filters

Last edit: Nov 10, 2025

Liquid filters in platformOS

In platformOS you can use all standard Liquid filters. Besides standard Liquid filters, you can also use platformOS-specific Liquid filters we added.

add_to_time

Adds a number of time units to a time

Params

  • time (stringnumberdatetime) - parsable time the units are added to; a number is read as whole seconds since the epoch
  • number (numberstring) - how many units to add — a string holding a number is accepted and a fractional number is truncated; optional, defaults to 1 - default: 1
  • unit (string) - time unit - allowed options are: y, years, mo, months, w, weeks, d [default], days, h, hours, m, minutes, s, seconds - default: 'd'

Returns

time - modified time

Examples


      {{ 'now' | add_to_time: 1, 'w' }} # => returns current time plus one week
    

      {{ 'now' | add_to_time: 3, 'mo' }} # => returns current time plus three months
    

advanced_format

Formats a value using a sprintf-style format string

Params

  • argument_to_format (untyped) - value you want to format; what it may be is decided by the format string — `%s` takes anything, `%.2f` a number or a time
  • format (string) - should look like: %[flags][width][.precision]type. For more examples and information see: https://ruby-doc.org/core-2.5.1/Kernel.html#method-i-sprintf

Returns

string - formatted string

Examples


      {{ 3.124 | advanced_format: '%.2f' }} => 3.12
    

      {{ 3 | advanced_format: '%.2f' }} => 3.00
In the example above flags is not present, width is not present (refers to the total final
length of the string), precision ".2" means 2 digits after the decimal point,
type "f" means floating point
    

amount_to_fractional

Converts amount in given currency to fractional. For example, convert USD to cents.

Params

  • amount (numberstring) - amount to be changed to fractional; a string holding a number and a money object are accepted too
  • currency (string) - currency to be used - default: 'USD'

Returns

number - Amount in fractional, for example cents for USD

Examples


      {{ 10.50 | amount_to_fractional: 'USD' }} => 1050
    

      {{ 10.50 | amount_to_fractional: 'JPY' }} => 11
    

array_add (aliases: add_to_array)

Appends an element to the end of the array

Params

  • array (array) - array to which you add a new element
  • item (untyped) - item you add to the array

Returns

array - array to which you add the item given as the second parameter

Examples


      {% assign array = 'a,b,c' | split: ',' %}
{{ array | array_add: 'd' }} => ['a', 'b', 'c', 'd']
    

array_any (aliases: any)

Checks whether the array contains at least one element equal to the query

Params

  • array (array) - array to search in - default: []
  • query (untyped) - value compared to each item in the given array - default: 'true'

Returns

boolean - checks if given array contains at least one of the queried string/number

Examples


      {% assign elements = 'foo,bar' | split: ',' %}
{{ elements | array_any: 'foo' }} => true
    

array_compact (aliases: compact)

Removes blank elements from the array

Params

  • array (array) - array with some blank values
  • property (string) - optionally if you provide Hash as argument, you can remove elements which given key is blank - default: nil

Returns

array - array from which blank values are removed

Examples


      {{ '1,' | split: ',' | array_add: false | array_add: '2' | array_compact }} => ["1","2"]
    

      {{ '1,' | split: ',' | array_add: null | array_add: '2' | array_compact }} => ["1","2"]
    

      {% assign empty_object = {} %}
{{ '1,' | split: ',' | array_add: empty_object | array_add: '2' | array_compact }} => ["1","2"]
    

      {% assign empty_array = ',' | split: ',' %}
{{ '1,' | split: ',' | array_add: empty_array | array_add: '2' | array_compact }} => ["1","2"]
    

      {% assign hash = [{ "hello": null }, { "hello": "world" }, { "hello": "" }] %}
{{ hash | array_compact: "hello" }} => [{"hello":"world"}]
    

array_delete

Removes every occurrence of the given element from the array

Params

  • array (array) - array to process
  • element (untyped) - value to remove

Returns

array - the initial array that has all occurences of "element" removed

Examples


      {% assign test = '["test", "test2", "test", "test3"]' | parse_json %}
{% assign arr = test | array_delete: 'test' %}
{{ arr }}  => ['test2', 'test3']
    

array_delete_at

Removes the element at the given index from the array

Params

  • array (array) - array to process
  • index (number) - array index to remove; must be a whole number within the array's bounds

Returns

array - the initial array that has the element at index removed

Examples


      {% assign test = '["test", "test2"]' | parse_json %}
{% assign arr = test | array_delete_at: 1 %}
{{ arr }}  => ['test']
    

array_detect (aliases: detect)

Returns the first element matching all the given field conditions

Params

  • objects (array) - array of objects to be processed
  • conditions (object) - hash with conditions { field_name: value } - default: {}

Keys other than these are accepted too.

Returns

untyped - first object from the collection that matches the specified conditions

Examples


      {{ objects }} => [{"foo":1,"bar":"a"},{"foo":2,"bar":"b"},{"foo":3,"bar":"c"}]
{{ objects | array_detect: foo: 2 }} => {"foo":2,"bar":"b"}
    

array_find_index

Finds the indices of every element matching all the given field conditions

Params

  • objects (array) - array of objects to be processed
  • conditions (object) - hash with conditions { field_name: value }

Keys other than these are accepted too.

Returns

array - with indices from collection that matches provided conditions

Examples


      {{ objects }} => [{"foo":1,"bar":"a"},{"foo":2,"bar":"b"},{"foo":3,"bar":"c"},{"foo":2,"bar":"d"}]
{{ objects | array_find_index: foo: 2 }} => [1, 3]
    

array_flatten (aliases: flatten)

Flattens an array of arrays into a single array

Params

  • array (array) - array of arrays to be processed

Returns

array - with objects

Examples


      {{ array_of_arrays }} => [[1,2], [3,4], [5,6]]
{{ array_of_arrays | array_flatten }} => [1,2,3,4,5,6]
    

array_group_by (aliases: group_by)

Transforms array into hash, with keys equal to the values of object's method name and value being array containing objects

Params

  • objects (array) - array to be grouped
  • method_name (string) - method name to be used to group Objects

Returns

object - the original array grouped by method specified by the second parameter

Examples


      {% assign objects = [
  { "size": "xl", "color": "red" },
  { "size": "xl", "color": "yellow" },
  { "size": "s", "color": "red" }
] %}
{{ objects | array_group_by: 'size' }} => {"xl":[{"size":"xl","color":"red"},{"size":"xl","color":"yellow"}],"s":[{"size":"s","color":"red"}]}
    

array_in_groups_of (aliases: in_groups_of)

Transforms array in array of arrays, each subarray containing exactly N elements

Params

  • array (array) - array to be split into groups
  • number_of_elements (number) - the size of each group the array is to be split into; must be a whole number

Returns

array - the original array split into groups of the size specified by the second parameter (an array of arrays)

Examples


      {% assign elements = '1,2,3,4' | split: ',' %}
{{ elements | array_in_groups_of: 3 }} => [[1, 2, 3], [4, null, null]]
    

array_index_of

Finds index of an object in the array

Params

  • array (array) - array of objects to be processed
  • object (untyped) - object to search for

Returns

number - position of the object in the array, or nil when it is not present

Examples


      {{ objects }} => [1,'abc',3]
{{ objects | array_index_of: 'abc' }} => 1
    

array_intersect (aliases: intersection)

Returns the elements present in both arrays

Params

  • array (array) - array of objects to be processed
  • other_array (array) - array of objects to be processed

Returns

array - that exists in both arrays

Examples


      {% liquid
  assign array = '1,2,3,4' | split: ','
  assign other_array = '3,4,5,6' | split: ','
%}

{{ array | array_intersect: other_array }} => [3,4]
    

array_limit (aliases: limit)

Returns at most the first N elements of the array

Params

  • array (array) - array to shrink
  • limit (number) - number of elements to be returned; must be a positive integer

Returns

array - the first `limit` elements; [1,2,3,4] limited to 2 elements gives [1,2]

Examples


      items => [{ id: 1, name: 'foo', label: 'Foo' }, { id: 2, name: 'bar', label: 'Bar' }]
{{ items | array_limit: 1 }} => [{ id: 1, name: 'foo', label: 'Foo' }]
    

array_map (aliases: map_attributes)

Extracts the values of the given keys from every object in the array

Params

  • array (array) - array of objects to be processed
  • attributes (array) - array of keys to be extracted; a key is a string for an array of hashes, or a whole number index for an array of arrays

Returns

array - array of arrays with values for given keys

Examples


      {{ items }} => [{ id: 1, name: 'foo', label: 'Foo' }, { id: 2, name: 'bar', label: 'Bar' }]
{{ items | array_map: 'id', 'name' }} => [[1, 'foo'], [2, 'bar']]
    

array_prepend (aliases: prepend_to_array)

Inserts an element at the beginning of the array

Params

  • array (array) - array to which you prepend a new element
  • item (untyped) - item you prepend to the array

Returns

array - array to which you prepend the item given as the second parameter

Examples


      {% assign array = 'a,b,c' | split: ',' %}
{{ array | array_prepend: 'd' }} => ['d', 'a', 'b', 'c']
    

array_reject (aliases: reject)

Returns every element that does not match all the given field conditions

Params

  • objects (array) - array of objects to be processed
  • conditions (object) - hash with conditions { field_name: value } - default: {}

Keys other than these are accepted too.

Returns

array - with objects from collection that don't match provided conditions

Examples


      {{ objects }} => [{"foo":1,"bar":"a"},{"foo":2,"bar":"b"},{"foo":3,"bar":"c"},{"foo":2,"bar":"d"}]
{{ objects | array_reject: foo: 2 }} => [{"foo":1,"bar":"a"},{"foo":3,"bar":"c"}]
    

array_rotate (aliases: rotate)

Rotates the array left by the given number of positions

Params

  • array (array) - array to be rotated
  • count (number) - number of times to rotate the input array; must be a whole number, optional, defaults to 1 - default: 1

Returns

array - the input array rotated by a number of times given as the second parameter; [1,2,3,4] rotated by 2 gives [3,4,1,2]

Examples


      {% assign numbers = "1,2,3" | split: "," %}
{{ numbers | array_rotate }} => [2,3,1]
    

array_select (aliases: select)

Returns every element matching all the given field conditions

Params

  • objects (array) - array of objects to be processed
  • conditions (object) - hash with conditions { field_name: value } - default: {}

Keys other than these are accepted too.

Returns

array - with objects from collection that matches provided conditions

Examples


      {{ objects }} => [{"foo":1,"bar":"a"},{"foo":2,"bar":"b"},{"foo":3,"bar":"c"},{"foo":2,"bar":"d"}]
{{ objects | array_select: foo: 2 }} => [{"foo":2,"bar":"b"},{"foo":2,"bar":"d"}]
    

array_shuffle (aliases: shuffle_array)

Returns the array with its elements in random order

Params

  • array (array) - array of objects to be processed

Returns

array - array with shuffled items

Examples


      {{ items }} => [1, 2, 3, 4]
{{ items | array_shuffle }} => [3, 2, 4, 1]
    

array_sort_by (aliases: sort_by)

Sorts an array of objects by the value of the given property

Params

  • input (array) - Array of Hash to be sorted by a key
  • property (untyped) - property by which to sort an Array of Hashes

Returns

array - Sorted object (Array of Hash)

Examples


      array1 is [{"title": "Tester", "value": 1}, {"title": "And", "value": 2}]
{{ array1 | array_sort_by: "title" }}
    

array_subtract (aliases: subtract_array)

Returns the elements of the first array that are not in the second

Params

  • array (array) - array of objects to be processed
  • other_array (array) - array of objects to be processed

Returns

array - that is a difference between two arrays

Examples


      {% liquid
  assign array = '1,2' | split: ','
  assign other_array = '2' | split: ','
%}

{{ array | array_subtract: other_array }} => [1]
    

array_sum (aliases: sum_array)

Sums all the numbers in the array

Params

  • array (array) - array with values to be summarised

Returns

number - summarised value of array

Examples


      {% assign numbers = '[1,2,3]' | parse_json %}
{{ numbers | array_sum }} => 6
    

array_uniq

Removes duplicate elements from an array

Params

  • input (untyped) - array to be processed; a single value is wrapped in an array first, so it comes back as a one-element array
  • property (untyped) - property to be used as the comparison key — a string key for an array of hashes, a whole number index for an array of arrays - default: nil

Returns

array - Returns an array with duplicate elements removed

Examples


      {% assign result = "[[1,2],[1,2],[3,4]]" | array_uniq %}
{{ result }} => "[[1,2],[3,4]]"
    

asset_url

Generates CDN url to an asset

Params

  • file_path (string) - path to the asset, relative to assets directory

Returns

string - CDN URL with the instance's asset cache buster appended.

Examples


      {{ "valid/file.jpg" | asset_url }} => https://cdn-server.com/instances/1/assets/valid/file.jpg?updated=1565632488
    

base64_decode

Decodes a Base64-encoded string

Params

  • base64_string (string) - Base64 encoded string

Returns

string - decoded string

Examples


      {{ 'aGVsbG8gYmFzZTY0\n' | base64_decode }} => 'hello base64'
    

base64_encode

Encodes a string as Base64, as defined by RFC 2045

Params

  • bin (string) - string to be encoded

Returns

string - Returns the Base64-encoded version of bin. This method complies with RFC 2045. Line feeds are added to every 60 encoded characters.

Examples


      {{ 'hello base64' | base64_encode }} => 'aGVsbG8gYmFzZTY0'
    

compute_hmac

Computes a keyed-hash message authentication code (HMAC) for the message

Params

  • data (string) - message to be authenticated
  • secret (string) - secret key
  • algorithm (string) - defaults to SHA256. Supported algorithms are: SHA, SHA1, SHA224, SHA256, SHA384, SHA512, MD4, MDC2, MD5, RIPEMD160, DSS1. - default: 'sha256'
  • digest (string) - defaults to hex. Supported digest values are hex, none, base64 - default: 'hex'

Returns

string - Keyed-hash message authentication code (HMAC), that can be used to authenticate requests from third party apps, e.g. Stripe webhooks requests

Examples


      {{ 'some_data' | compute_hmac: 'some_secret', 'MD4' }} => 'cabff538af5f97ccc27d481942616492'
    

date_add (aliases: add_to_date)

Adds a number of time units to a date

Params

  • time (stringnumberdatetime) - parsable time the units are added to; a number is read as whole seconds since the epoch
  • number (numberstring) - how many units to add — a string holding a number is accepted and a fractional number is truncated; optional, defaults to 1 - default: 1
  • unit (string) - time unit - allowed options are: y, years, mo, months, w, weeks, d [default], days, h, hours, m, minutes, s, seconds - default: 'd'

Returns

date - modified Date

Examples


      {{ '2010-01-01' | date_add: 1 }} => 2010-01-02
{{ '2010-01-01' | date_add: 1, 'mo' }} => 2010-02-01
    

decrypt

Filter allowing to decrypt data encrypted with a specified algorithm. See encrypt filter for encryption.

Params

  • payload (string) - string payload to be decrypted - must be a Base64 encoded (RFC 4648) or HEX (if from_hex flag true) string
  • algorithm (string) - algorithm you want to use for encryption. Supported symmetric algorithms: aes-128-cbc, aes-128-cbc-hmac-sha1, aes-128-cbc-hmac-sha256, aes-128-ccm, aes-128-cfb, aes-128-cfb1, aes-128-cfb8, aes-128-ctr, aes-128-ecb, aes-128-gcm, aes-128-ocb, aes-128-ofb, aes-128-xts, aes-192-cbc, aes-192-ccm, aes-192-cfb, aes-192-cfb1, aes-192-cfb8, aes-192-ctr, aes-192-ecb, aes-192-gcm, aes-192-ocb, aes-192-ofb, aes-256-cbc, aes-256-cbc-hmac-sha1, aes-256-cbc-hmac-sha256, aes-256-ccm, aes-256-cfb, aes-256-cfb1, aes-256-cfb8, aes-256-ctr, aes-256-ecb, aes-256-gcm, aes-256-ocb, aes-256-ofb, aes-256-xts, aes128, aes128-wrap, aes192, aes192-wrap, aes256, aes256-wrap, aria-128-cbc, aria-128-ccm, aria-128-cfb, aria-128-cfb1, aria-128-cfb8, aria-128-ctr, aria-128-ecb, aria-128-gcm, aria-128-ofb, aria-192-cbc, aria-192-ccm, aria-192-cfb, aria-192-cfb1, aria-192-cfb8, aria-192-ctr, aria-192-ecb, aria-192-gcm, aria-192-ofb, aria-256-cbc, aria-256-ccm, aria-256-cfb, aria-256-cfb1, aria-256-cfb8, aria-256-ctr, aria-256-ecb, aria-256-gcm, aria-256-ofb, aria128, aria192, aria256, bf, bf-cbc, bf-cfb, bf-ecb, bf-ofb, blowfish, camellia-128-cbc, camellia-128-cfb, camellia-128-cfb1, camellia-128-cfb8, camellia-128-ctr, camellia-128-ecb, camellia-128-ofb, camellia-192-cbc, camellia-192-cfb, camellia-192-cfb1, camellia-192-cfb8, camellia-192-ctr, camellia-192-ecb, camellia-192-ofb, camellia-256-cbc, camellia-256-cfb, camellia-256-cfb1, camellia-256-cfb8, camellia-256-ctr, camellia-256-ecb, camellia-256-ofb, camellia128, camellia192, camellia256, cast, cast-cbc, cast5-cbc, cast5-cfb, cast5-ecb, cast5-ofb, chacha20, chacha20-poly1305, des, des-cbc, des-cfb, des-cfb1, des-cfb8, des-ecb, des-ede, des-ede-cbc, des-ede-cfb, des-ede-ecb, des-ede-ofb, des-ede3, des-ede3-cbc, des-ede3-cfb, des-ede3-cfb1, des-ede3-cfb8, des-ede3-ecb, des-ede3-ofb, des-ofb, des3, des3-wrap, desx, desx-cbc, id-aes128-CCM, id-aes128-GCM, id-aes128-wrap, id-aes128-wrap-pad, id-aes192-CCM, id-aes192-GCM, id-aes192-wrap, id-aes192-wrap-pad, id-aes256-CCM, id-aes256-GCM, id-aes256-wrap, id-aes256-wrap-pad, id-smime-alg-CMS3DESwrap, idea, idea-cbc, idea-cfb, idea-ecb, idea-ofb, rc2, rc2-128, rc2-40, rc2-40-cbc, rc2-64, rc2-64-cbc, rc2-cbc, rc2-cfb, rc2-ecb, rc2-ofb, rc4, rc4-40, rc4-hmac-md5, seed, seed-cbc, seed-cfb, seed-ecb, seed-ofb, sm4, sm4-cbc, sm4-cfb, sm4-ctr, sm4-ecb, sm4-ofb Supported asymmetric algorithms: RSA, RSA-OAEP
  • key (string) - a key used for encryption. Key must match the algorithm requirments. For asymmetric algorithms there are public and private keys that need to passed in PEM format.
  • options (object) - additional options to control the decryption algorithm - default: {}

Named options

  • transform_key_to_hex (boolean) - - transfrom key to HEX
  • from_hex (boolean) - - return HEX enxrypted string instead of Base64 encoded
  • disable_cipher_padding (boolean) - - disable cipher padding

Returns

string - String - decrypted string using the algorithm of your choice. Initialization Vector (iv) is expected to be present in the encrypted payload at the beginning.

Examples


      {{ some_payload | decrypt: 'aes-256-cbc', 'ThisPasswordIsReallyHardToGuessA' }} => decrypted string from payload
{{ "43553EEDD9BFE36D10F99E931245CF8826903C00D235DFD300B3CC40BD263A621FC2FB9F5C3743F75D399A912AFABF92371927C6D190E0EFF19EAE9802320391FED79D92009796403EC6B426E901AB981CE53A43557C295F3D6FC9678EE0557F" | decrypt: 'aes-128-ecb', '4FCD5FAE2AC493C0F8CE8E1E6105D194', transform_key_to_hex: true, from_hex: true, disable_cipher_padding: true }} => iframe=true;customer.firstName=John;customer.lastName=Smith;header.accountNumber=6759370;header.authToken1=12345;header.paymentTypeCode=UTILITY;header.amount=123.45

AES-256-GCM (authenticated decryption, payload format: IV + ciphertext + auth_tag):
{% assign key = 'ThisIsA32ByteKeyForAES256GCM!!!!' %}
{% assign encrypted = 'foo bar' | encrypt: 'aes-256-gcm', key %}
{{ encrypted | decrypt: 'aes-256-gcm', key }} => foo bar

AES-128-GCM:
{% assign encrypted = 'secret data' | encrypt: 'aes-128-gcm', '16ByteSecretKey!' %}
{{ encrypted | decrypt: 'aes-128-gcm', '16ByteSecretKey!' }} => secret data

chacha20-poly1305 (authenticated decryption):
{% assign encrypted = 'baz qux' | encrypt: 'chacha20-poly1305', '32ByteKeyForChaCha20Poly1305!!!!' %}
{{ encrypted | decrypt: 'chacha20-poly1305', '32ByteKeyForChaCha20Poly1305!!!!' }} => baz qux

AES-256-GCM with hex key:
{% assign decrypted = encrypted | decrypt: 'aes-256-gcm', hex_key, transform_key_to_hex: true, from_hex: true %}
    

deep_clone

Returns a deep copy of the object, so nested values can be changed independently

Params

  • object (untyped) - object to be duplicated

Returns

untyped - returns a copy of the object parameter

Examples


      {% assign some_hash_copy = some_hash | deep_clone %}
    

digest

Returns a cryptographic hash of the string, using the chosen algorithm

Params

  • object (string) - message that you want to obtain a cryptographic hash for
  • algorithm (string) - the hash algorithm to use. Choose from: 'md5', 'sha1', 'sha256', 'sha384', 'sha512'. Default is sha1. - default: 'sha1'
  • digest (string) - defaults to hex. Supported digest values are hex, none, base64 - default: 'hex'

Returns

string - hexadecimal hash value obtained by applying the selected algorithm to the message

Examples


      {{ 'foo' | digest }} => '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33'
{{ 'foo' | digest: 'sha256' }} => '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae'
{{ 'foo' | digest: 'sha256', 'base64' }} => 'LCa0a2j/xo/5m0U8HTBBNBNCLXBkg7+g+YpeiGJm564='
{{ 'foo' | digest: 'sha256', 'none' | base64_encode }} => LCa0a2j/xo/5m0U8HTBBNBNCLXBkg7+g+YpeiGJm564= # 'none' returns the raw binary digest
    

download_file

Downloads a remote file and returns its body

Params

  • url (string) - url to a remote file
  • max_size (number) - max file size of the file, default 1 megabyte. Can't exceed 50 megabytes. - default: 1

Returns

string - Body of the remote file

Examples


      {{ 'http://www.example.com/my_file.txt' | download_file }} => "Content of a file"
{% assign data = 'https://example.com/data.json' | download_file | parse_json %}
    

ecdh_compute

Computes an ECDH shared secret from your private key and a peer's public key

Params

  • private_key (string) - your EC private key, PEM-encoded
  • peer_public_key (string) - the peer's EC public key. Accepts either: - a PEM-encoded EC public key (`-----BEGIN PUBLIC KEY-----...`), or - a raw, uncompressed EC point, Base64url-encoded (RFC 4648 §5, padding optional) - this is the format returned by a browser's `PushSubscription.getKey('p256dh')` for Web Push. The curve is always taken from `private_key`'s own curve; both keys must use the same curve (P-256/`prime256v1` for Web Push).
  • output (string) - defaults to 'none' (raw bytes - ready to be piped straight into the +hkdf+ filter). Supported values are hex, none, base64 (Base64 here is URL-safe/RFC 4648 §5, matching Web Push/JOSE conventions - note this differs from the standard, non-URL-safe base64 produced by the `digest`/`compute_hmac` filters). - default: 'none'

Returns

string - the ECDH (Elliptic Curve Diffie-Hellman) shared secret computed from your EC private key and a peer's EC public key. Intended as a building block for implementing key-agreement schemes - such as Web Push message encryption (RFC 8291/8292) - entirely from Liquid, together with the +hkdf+ filter.

Examples


      Web Push (RFC 8291) - deriving the ECDH shared secret between your EC private key and a subscriber's
'p256dh' key:
{% assign shared_secret = as_private_key | ecdh_compute: subscription.keys.p256dh %}
    

      Two parties independently agreeing on the same secret:
{% assign alice_secret = alice_private_key | ecdh_compute: bob_public_key, 'hex' %}
{% assign bob_secret = bob_private_key | ecdh_compute: alice_public_key, 'hex' %}
{% if alice_secret == bob_secret %}true{% endif %} => true
    

encode

The filter returns a string with the encoding changed to the one specified by the 'destination_encoding' parameter. The filter changes the string itself (its representation in memory) by first determining which graphical characters the underlying bytes in the string represent in the 'source_encoding', and then changing the bytes to encode the same graphical characters in 'destination_encoding'.

Params

  • text (string) - input string that we want to reencode
  • destination_encoding (string) - the encoding we want the source string text converted to
  • source_encoding (string) - the encoding of the source string text

Returns

string - input string with encoding modified from source_encoding to destination_encoding

Examples


      {{ 'John arrived_foo' | encode: 'ISO-8859-1', 'UTF-8' }} => John arrived_foo
{% comment %}
  invalid:, undefined: and replace: are Ruby KEYWORD arguments, which a template cannot
  reach: Liquid collects named filter arguments into a single trailing positional Hash,
  and Ruby 3 does not convert that back into keywords. Passing them raises
  "encode filter - wrong number of arguments (given 4, expected 3)" — measured, and the
  reason the previous version of this example could never have worked.
{% endcomment %}
    

encoding

The filter returns the encoding of the string parameter (i.e. how the underlying bytes in the string are interpreted to determine which graphical characters they encode).

Params

  • text (string) - input string whose encoding we want to find

Returns

string - encoding of the string text

Examples


      {{ 'John arrived_foo' | encoding }} => 'UTF-8'
    

encrypt

Filter allowing to encrypt data with specified algorithm. See decrypt filter for decryption

Params

  • payload (string) - string payload to be encrypted
  • algorithm (string) - algorithm you want to use for encryption. Supported symmetric algorithms: aes-128-cbc, aes-128-cbc-hmac-sha1, aes-128-cbc-hmac-sha256, aes-128-ccm, aes-128-cfb, aes-128-cfb1, aes-128-cfb8, aes-128-ctr, aes-128-ecb, aes-128-gcm, aes-128-ocb, aes-128-ofb, aes-128-xts, aes-192-cbc, aes-192-ccm, aes-192-cfb, aes-192-cfb1, aes-192-cfb8, aes-192-ctr, aes-192-ecb, aes-192-gcm, aes-192-ocb, aes-192-ofb, aes-256-cbc, aes-256-cbc-hmac-sha1, aes-256-cbc-hmac-sha256, aes-256-ccm, aes-256-cfb, aes-256-cfb1, aes-256-cfb8, aes-256-ctr, aes-256-ecb, aes-256-gcm, aes-256-ocb, aes-256-ofb, aes-256-xts, aes128, aes128-wrap, aes192, aes192-wrap, aes256, aes256-wrap, aria-128-cbc, aria-128-ccm, aria-128-cfb, aria-128-cfb1, aria-128-cfb8, aria-128-ctr, aria-128-ecb, aria-128-gcm, aria-128-ofb, aria-192-cbc, aria-192-ccm, aria-192-cfb, aria-192-cfb1, aria-192-cfb8, aria-192-ctr, aria-192-ecb, aria-192-gcm, aria-192-ofb, aria-256-cbc, aria-256-ccm, aria-256-cfb, aria-256-cfb1, aria-256-cfb8, aria-256-ctr, aria-256-ecb, aria-256-gcm, aria-256-ofb, aria128, aria192, aria256, bf, bf-cbc, bf-cfb, bf-ecb, bf-ofb, blowfish, camellia-128-cbc, camellia-128-cfb, camellia-128-cfb1, camellia-128-cfb8, camellia-128-ctr, camellia-128-ecb, camellia-128-ofb, camellia-192-cbc, camellia-192-cfb, camellia-192-cfb1, camellia-192-cfb8, camellia-192-ctr, camellia-192-ecb, camellia-192-ofb, camellia-256-cbc, camellia-256-cfb, camellia-256-cfb1, camellia-256-cfb8, camellia-256-ctr, camellia-256-ecb, camellia-256-ofb, camellia128, camellia192, camellia256, cast, cast-cbc, cast5-cbc, cast5-cfb, cast5-ecb, cast5-ofb, chacha20, chacha20-poly1305, des, des-cbc, des-cfb, des-cfb1, des-cfb8, des-ecb, des-ede, des-ede-cbc, des-ede-cfb, des-ede-ecb, des-ede-ofb, des-ede3, des-ede3-cbc, des-ede3-cfb, des-ede3-cfb1, des-ede3-cfb8, des-ede3-ecb, des-ede3-ofb, des-ofb, des3, des3-wrap, desx, desx-cbc, id-aes128-CCM, id-aes128-GCM, id-aes128-wrap, id-aes128-wrap-pad, id-aes192-CCM, id-aes192-GCM, id-aes192-wrap, id-aes192-wrap-pad, id-aes256-CCM, id-aes256-GCM, id-aes256-wrap, id-aes256-wrap-pad, id-smime-alg-CMS3DESwrap, idea, idea-cbc, idea-cfb, idea-ecb, idea-ofb, rc2, rc2-128, rc2-40, rc2-40-cbc, rc2-64, rc2-64-cbc, rc2-cbc, rc2-cfb, rc2-ecb, rc2-ofb, rc4, rc4-40, rc4-hmac-md5, seed, seed-cbc, seed-cfb, seed-ecb, seed-ofb, sm4, sm4-cbc, sm4-cfb, sm4-ctr, sm4-ecb, sm4-ofb Supported asymmetric algorithms: RSA, RSA-OAEP
  • key (string) - a key used for encryption. Key must match the algorithm requirments. For asymmetric algorithms there are public and private keys that need to passed in PEM format.
  • iv (string) - initialization vector, raw bytes, must match the algorithm's IV length; optional (e.g. 12 or 16 bytes for aes-*-gcm, 16 bytes for aes-*-cbc). If not provided, one is generated randomly. Not supported for asymmetric algorithms (RSA, RSA-OAEP). - default: nil
  • options (object) - additional options to control the encrypt algorithm - default: {}

Named options

  • transform_key_to_hex (boolean) - - transfrom key to HEX
  • return_hex (boolean) - - return HEX encrypted string instead of Base64 encoded
  • pad_payload_right (number) - - integer value of block length

Returns

string - Base64 encoded (RFC 4648) (or HEX if return_hex is true) encrypted string using the algorithm of your choice. Initialization Vector (iv) will be appended

Examples


      {% capture payload %}
  {
   "key": "value",
   "another_key": "another value"
  }
{% endcapture %}
{{ payload | encrypt: 'aes-256-cbc', 'ThisPasswordIsReallyHardToGuessA' }} => Kkuo2eWEnTbcrtbGjAmQVMTjptS5elsgqQe-5blHpUR-ziHPI45n2wOnY30DVZGldCTNqMT_Ml0ZFiGiupKGD4ZWxVIMkdCHaq4XgiAIUew=
{{ "step=2;header.amount=10;header.paymentTypeCode=ONLINE;customer.firstName=John" | encrypt: 'aes-128-ecb', '4C6C821832AAFFF2749852CEED2FE74F', null, transform_key_to_hex: true, return_hex: true, pad_payload_right: 32 }} => 43553EEDD9BFE36D10F99E931245CF8826903C00D235DFD300B3CC40BD263A621FC2FB9F5C3743F75D399A912AFABF92371927C6D190E0EFF19EAE9802320391FED79D92009796403EC6B426E901AB981CE53A43557C295F3D6FC9678EE0557F

AES-256-GCM (authenticated encryption):
{% assign key = 'ThisIsA32ByteKeyForAES256GCM!!!!' %}
{% assign encrypted = 'foo bar' | encrypt: 'aes-256-gcm', key %}
{{ encrypted }} => Base64 encoded string containing IV + ciphertext + auth_tag

AES-128-GCM:
{% assign encrypted = 'secret data' | encrypt: 'aes-128-gcm', '16ByteSecretKey!' %}

chacha20-poly1305 (authenticated encryption):
{% assign encrypted = 'sensitive payload' | encrypt: 'chacha20-poly1305', '32ByteKeyForChaCha20Poly1305!!!!' %}

AES-256-GCM with hex key:
{% assign encrypted = 'foo bar' | encrypt: 'aes-256-gcm', hex_key, null, transform_key_to_hex: true, return_hex: true %}

AES-128-GCM with an explicit, caller-supplied IV (e.g. a nonce derived elsewhere, as in RFC 8291 Web Push):
{% assign encrypted = 'secret data' | encrypt: 'aes-128-gcm', '16ByteSecretKey!', derived_nonce %}
    

end_with

Check if string ends with given substring(s)

Params

  • string (string) - string to check ends with any of the provided suffixes
  • suffixes (stringarray) - suffix to check, or an array of suffixes of which any one matching is enough

Returns

boolean - true if string ends with a suffixes

Examples


      {{ 'my_example' | end_with: 'example' }} => true
    

      {{ 'my_example' | end_with: 'my' }} => false
    

      {% assign suffixes = ["array", "example"] %}
{{ 'my_example' | end_with: suffixes }} => true
    

escape_javascript

Escapes newlines, quotes and backslashes so the text is safe inside a JavaScript string

Params

  • text (string) - text to be escaped

Returns

string - escaped text, safe to embed in a JavaScript string literal

Examples


      {{ "it's a \"test\"" | escape_javascript }} => it\'s a \"test\"
    

expand_url_template

Creates url based on provided named parameters to the template

Params

  • template (string) - URL template. Read more at https://tools.ietf.org/html/rfc6570
  • params (object) - hash with data injected into template

Keys other than these are accepted too.

Returns

string - expanded URL

Examples


      {% assign template = "/search/{city}/{street}" %}
{{ template | expand_url_template: city: "Sydney", street: "BlueRoad" }}
=> /search/Sydney/BlueRoad
    

      {% assign template = "/search{?city,street}" %}
{{ template | expand_url_template: city: "Sydney", street: "BlueRoad" }}
=> /search?city=Sydney&street=BlueRoad
    

extract_url_params

Extracts named parameters from the url

Params

  • url (string) - URL with params to extract
  • templates (stringarray) - URL template, or an array of templates of which the first match wins. Read more at https://tools.ietf.org/html/rfc6570

Returns

object - hash with extracted params

Examples


      {% assign template = "/search/{city}/{street}" %}
{{ "/search/Sydney/BlueRoad" | extract_url_params: template  }} => {"city":"Sydney","street":"BlueRoad"}
    

      {% assign template = "/{first}{/second*}" %}
{{ "/a/b/c/" | extract_url_params: template }} => {"first":"a","second":["b","c"]}
    

      {% assign template = "/{first}/{second}{?limit,offset}" %}
{{ "/my/path?limit=10&offset=0" | extract_url_params: template }} => {"first":"my","second":"path","limit":"10","offset":"0"}
    

      {% assign template = "/search/{+query}" %}
{% assign params = "/search/this+is+my+query" | extract_url_params: template %}
{{ params }} => {"query":"this+is+my+query"}
{{ params.query | split: '+' }} => ["this","is","my","query"]
    

      {% assign template = "{+location}/listings" %}
{{ "/Warsaw/Poland/listings" | extract_url_params: template }} => {"location":"/Warsaw/Poland"}
    

force_encoding

The filter returns a string with the encoding changed to the one specified by the 'encoding' parameter. The filter does not change the string itself (its representation in memory) but changes how the underlying bytes in the string are interpreted to determine which characters they encode

Params

  • text (string) - input string whose encoding we want modified
  • encoding (string) - name of the encoding the bytes should be interpreted as

Returns

string - input string with encoding modified to the one specified by the encoding parameter

Examples


      {{ 'John arrived_foo' | force_encoding: "ISO-8859-1" }}
    

format_number

Formats a number using the given precision, delimiter and separator

Params

  • number (numberstringtime) - integer or float to format, a string holding one — a non-numeric string is read as 0 — or a time, which formats as its seconds since the epoch
  • options (object) - formatting options - default: {}

Named options

  • locale (string) - Sets the locale to be used for formatting (defaults to current locale).
  • precision (number) - Sets the precision of the number (defaults to 3).
  • significant (boolean) - If true, precision will be the number of significant_digits. If false, the number of fractional digits (defaults to false).
  • separator (string) - Sets the separator between the fractional and integer digits (defaults to ".").
  • delimiter (string) - Sets the thousands delimiter (defaults to "").
  • strip_insignificant_zeros (boolean) - If true removes insignificant zeros after the decimal separator (defaults to false).
  • round_mode (string) - Sets how the number is rounded — one of up, down, ceiling, floor, half_up, half_down, half_even, banker or none (defaults to half_up).

Returns

string - formatted number

Examples


      {{ 111.2345 | format_number }} # => 111.235
    

      {{ 111.2345 | format_number: precision: 2 }} # => 111.23
    

      {{ 111 | format_number: precision: 2 }} # => 111.00
    

      {{ 1111.2345 | format_number: precision: 2, separator: ',', delimiter: '.' }} # => 1.111,23
    

fractional_to_amount

Converts currency in fractional to whole amount. For example, convert cents to USD.

Params

  • amount (numberstring) - fractional amount; must be a whole number (or a string holding one), a money object is accepted too
  • currency (string) - currency to be used - default: 'USD'

Returns

number - converted fractional amount

Examples


      {{ 1050 | fractional_to_amount: 'USD' }} => 10.5
    

      {{ 1050 | fractional_to_amount: 'JPY' }} => 1050
    

gzip_compress

Gzip compress a string

Params

  • uncompressed_string (string) - string to be compressed {% assign result = "Lorem ipsum" | gzip_compress | gzip_decompress %} {{ result }} => "Lorem ipsum"

Returns

string - Gzip-compressed string

gzip_decompress

Gzip decompress a string

Params

  • compressed_string (string) - string to be decompressed {% assign result = "Lorem ipsum" | gzip_compress | gzip_decompress %} {{ result }} => "Lorem ipsum"

Returns

string - Decompressed string

hash_add_key (aliases: add_hash_keyassign_to_hash_key)

Returns the hash with the given key set to the given value

Params

  • hash (object) - hash to add the key to
  • key (untyped) - key to add; usually a string, but any value can be a key
  • value (untyped) - value to store under the key

Returns

object - hash with added key

Examples


      {% liquid
  assign accountants = "Angela,Kevin,Oscar" | split: ","
  assign management = "David,Jan,Michael" | split: ","
  assign company = {}
  assign company = company | hash_add_key: "name", "Dunder Mifflin"
  assign company = company | hash_add_key: "accountants", accountants
  assign company = company | hash_add_key: "management", management
%}
{{ company }} => {"name" => "Dunder Mifflin", "accountants" => ["Angela", "Kevin", "Oscar"], "management" => ["David", "Jan", "Michael"]}
    

hash_delete_key (aliases: delete_hash_keyremove_hash_key)

Removes the given key from the hash and returns the value it held

Params

  • hash (object) - hash to remove the key from
  • key (string) - key to remove

Returns

untyped - value which was assigned to a deleted key. If the key did not exist in the first place, null is returned.

Examples


      {% liquid
  assign hash = '{ "a": "1", "b": "2"}' | parse_json
  assign a_value = hash | hash_delete_key: "a"
%}
{{ a_value }} => "1"
{{ hash }} => { "b": "2" }
    

hash_diff

Generates a list of additions (+), deletions (-) and changes (~) from given two ojects.

Params

  • hash1 (object) - hash to compare from
  • hash2 (object) - hash to compare to
  • options (object) - optional options forwarded to the underlying diff (e.g. similarity) - default: {}

Named options

  • similarity (number) - How alike two array elements must be to count as changed rather than added and removed (defaults to 0.8)
  • strict (boolean) - Compares values of different types as unequal, so 1 and 1.0 differ (defaults to true)
  • indifferent (boolean) - Treats a string key and a symbol key as the same key (defaults to false)
  • strip (boolean) - Strips whitespace from string values before comparing them (defaults to false)
  • case_insensitive (boolean) - Compares string values ignoring case (defaults to false)
  • numeric_tolerance (number) - Treats two numbers within this distance of each other as equal
  • delimiter (string) - Separates the segments of the reported key path (defaults to ".")
  • ignore_keys (array) - Keys to leave out of the comparison entirely
  • array_path (boolean) - Reports each key path as an array of segments instead of one joined string (defaults to false)
  • use_lcs (boolean) - Matches array elements with a longest-common-subsequence pass (defaults to true)

Keys other than these are accepted too.

Returns

array - array containg the difference between two hashes

Examples


      {% liquid
  assign a = '{ "a": 1, "c": "5 ", "d": 6, "e": { "f": 5.12 } }' | parse_json
  assign b = '{ "b": 2, "c": "5",  "d": 5, "e": { "f": 5.13 } }' | parse_json
%}
{{ a | hash_diff: b }} => [["-","a",1],["~","c","5 ","5"],["~","d",6,5],["~","e.f",5.12,5.13],["+","b",2]]
{{ a | hash_diff: b, strip: true }}  => [["-","a",1],["~","d",6,5],["~","e.f",5.12,5.13],["+","b",2]]
    

hash_dig (aliases: dig)

Extracts a nested value by following the given sequence of keys

Params

  • hash (object) - hash to traverse
  • keys (array) - comma separated sequence of keys to dig down the hash; a key is a string, or a whole number where the value being stepped into is an array — `hash_dig: 'images', 0, 'url'`

Returns

untyped - Extracted nested value specified by the sequence of keys by calling dig at each step, returning null if any intermediate step is null.

Examples


      {% assign user_json = { "name": { "first": "John", "last": "Doe" } } %}
{{ user_json | hash_dig: "name", "first" }} => John
    

hash_except

Returns the hash without the given keys

Params

  • hash (object) - input hash
  • except (array) - array of keys that should be removed

Returns

object

Examples


      {% liquid
  assign data = null | hash_merge: foo: 'fooval', bar: 'barval', baz: 'bazval'
%}
{% assign exc = 'foo,baz' | split: ',' %}
{{ data | hash_except: exc }} => { "bar": "barval" }
    

hash_keys

Returns the hash's keys

Params

  • hash (object) - input hash

Returns

array

Examples


      {% liquid
  assign data = null | hash_merge: foo: 'fooval', bar: 'barval'
%}

{{ data | hash_keys }} => ["foo", "bar"]
    

hash_merge

Merges two hashes; where both define a key, the second hash wins

Params

  • hash1 (object) - hash to merge into
  • hash2 (object) - hash whose keys are merged in, overwriting duplicates

Returns

object - new hash containing the contents of hash1 and the contents of hash2. On duplicated keys we keep value from hash2

Examples


      {% liquid
  assign a = '{"a": 1, "b": 2 }' | parse_json
  assign b = '{"b": 3, "c": 4 }' | parse_json
  assign new_hash = a | hash_merge: b
%}
{{ new_hash }} => { "a": 1, "b": 3, "c": 4 }
    

      {% liquid
  assign a = {"a": 1}
  assign a = a | hash_merge: b: 2, c: 3
%}
{{ a }} => { "a": 1, "b": 2, "c": 3 }
    

hash_sort

Returns the hash with its keys sorted alphabetically

Params

  • input (object) - Hash to be sorted

Returns

object - Sorted hash

Examples


      {% assign hash1 = '{"key2": "value2", "key1": "value1"}' | parse_json %}
{{ hash1 | hash_sort }} => {"key1": "value1", "key2": "value2"}
    

      {% assign hash1 = '{"a": 1, "c": 2, "b": 3}' | parse_json %}
{{ hash1 | hash_sort }} => {"a": 1, "b": 3, "c": 2}
    

hash_values

Returns the hash's values

Params

  • hash (object) - input hash

Returns

array

Examples


      {% liquid
  assign data = null | hash_merge: foo: 'fooval', bar: 'barval'
%}

{{ data | hash_values }} => ["fooval", "barval"]
    

hcaptcha

Verifies an hCaptcha challenge from the submitted params

Params

  • params (object) - params sent to the server

Keys other than these are accepted too.

Returns

boolean - whether the parameters are valid hcaptcha verification parameters

Examples


      {{ context.params | hcaptcha }} => true
    

hkdf

Derives key material from input key material, using HKDF

Params

  • ikm (string) - input keying material - raw bytes, e.g. the output of +ecdh_compute+
  • salt (string) - optional salt value (a non-secret random value); defaults to an empty string, which per RFC 5869 is equivalent to a string of HashLen zero bytes - default: ''
  • info (string) - optional context and application specific information; defaults to an empty string - default: ''
  • length (number) - the desired output length in octets; defaults to 32 (the digest size of SHA-256). Must be less than or equal to 255 * HashLen (per RFC 5869) - default: 32
  • hash_algorithm (string) - the underlying hash algorithm; defaults to 'sha256' (matching RFC 8291's use of HKDF-SHA256). Any digest supported by OpenSSL::Digest can be used - default: 'sha256'

Returns

string - the output keying material (OKM), raw bytes, derived via HKDF (HMAC-based Extract-and-Expand Key Derivation Function, RFC 5869), combining the Extract and Expand steps in a single call. Useful together with +ecdh_compute+ to implement Web Push message encryption (RFC 8291), or any other HKDF-based scheme, entirely from Liquid.

Examples


      RFC 5869 Appendix A.1, Test Case 1 (SHA-256, basic):
{% assign okm = ikm | hkdf: salt, info, 42, 'sha256' %}
    

      Web Push (RFC 8291) - deriving a Content Encryption Key from an intermediate key and a random salt:
{% assign cek = ikm | hkdf: salt, cek_info, 16 %}
    

html_safe

Marks the string as safe to render as HTML, so its tags are not escaped

Params

  • text (string) - text to render as HTML
  • options (object) - set raw_text to true to stop it from unescaping HTML entities - default: {}

Named options

  • raw_text (boolean) - Marks the string as safe as written instead of unescaping HTML entities first (defaults to false)

Returns

string - string that can be rendered with all HTML tags, by default all variables are escaped.

Examples


      {{ '<h1>Hello</h1>' }} => '&lt;h1&gt;Hello&lt;/h1>&gt;'
    

      {{ '<h1>Hello</h1>' | html_safe }} => '<h1>Hello</h1>'
    

      {{ '<script>alert("Hello")</script>' }} => <script>alert("Hello")</script> - this will just print text in the source code of the page
    

      {{ '<script>alert("Hello")</script>' | html_safe }} => <script>alert("Hello")</script> - this script will be evaluated when a user enters the page
    

      {{ 'abc &quot; def' | html_safe: raw_text: true }} => 'abc &quot; def'
    

      {{ 'abc &quot; def' | html_safe: raw_text: false }} => 'abc " def'
    

html_to_text

Converts HTML into plain text

Params

  • html (string) - html to be converted to text
  • options (object) - optional. Default root_element: null, remove_nodes: 'script, link, style', replace_newline: ' ' - default: {}

Named options

  • root_element (string) - css selector of node which content should be returned, default is null
  • remove_nodes (string) - CSS selector of nodes that should be ignored, default is 'script, link, style'
  • replace_newline (string) - specifies a character to be used to replace newlines, default is ' ' (new lines will be converted to space)

Returns

string - text without any html tags

Examples


      {{ '<h1>Hello <a href="#">world</a></h1>' | html_to_text }} => Hello world
    

humanize

Turns a machine-readable key into a human-readable string

Params

  • key (string) - input string to be transformed

Returns

string - a human readable string derived from the input; capitalizes the first word, turns underscores into spaces, and strips a trailing '_id' if present. Used for creating a formatted output (e.g. by replacing underscores with spaces, capitalizing the first word, etc.).

Examples


      {{ 'car_model' | humanize }} => 'Car model'
    

      {{ 'customer_id' | humanize }} => 'Customer'
    

is_date_before (aliases: date_before)

Checks whether the first time is earlier than the second

Params

  • first_time (stringnumberdatetime) - time to compare to the second parameter; a number is read as whole seconds since the epoch
  • second_time (stringnumberdatetime) - time against which the first parameter is compared to

Returns

boolean - returns true if the first time is lower than the second time

Examples


      {{ '2010-01-02' | date_before: '2010-01-03' }} => true
    

      {{ '6 months ago' | date_before: '2010-01-03' }} => false
    

      {{ '1 day ago' | date_before: 'now' }} => true
    

is_date_in_past

Checks whether the time is in the past

Params

  • time (stringnumberdatetime) - time object, can also be a string; a number is read as whole seconds since the epoch

Returns

boolean - true if time passed is in the past, false otherwise

Examples


      {{ '2010-01-01' | is_date_in_past }} => true
    

      {{ '3000-01-01' | is_date_in_past }} => false
    

is_email_valid

Checks whether the string is a valid email address

Params

  • email (string) - String containing potentially valid email

Returns

boolean - whether or not the argument is a valid email

Examples


      {% assign valid = '[email protected]' | is_email_valid %}
valid => true

{% assign valid = 'john@' | is_email_valid %}
valid => false
    

is_gpg_valid

Checks if a given string is a valid GPG key

Params

  • key (string) - key to be checked for validity {% assign valid_gpg = "..." | is_gpg_valid %} {{ result }} => false

Returns

boolean - whether the input value is a valid GPG key or not

is_json_valid

Checks whether the string is valid JSON

Params

  • text (untyped) - String containing potentially valid JSON; any other type is simply not valid JSON, so the answer is false rather than an error

Returns

boolean - whether or not the argument is a valid JSON

Examples


      {% assign valid = '{ "name": "foo", "bar": {} }' | is_json_valid %}
valid => true

{% assign valid = '{ "foo" }' | is_json_valid %}
valid => false
    

is_parsable_date

Checks whether the value can be parsed as a date

Params

  • object (untyped) - object that can be a date

Returns

boolean - whether the parameter can be parsed as a date

Examples


      {{ '2021/2' | is_parsable_date }} => true
    

is_token_valid

Temporary token is valid for desired number of hours (by default 48), which you can use to authorize the user in third party application. To do it, include it in a header with name UserTemporaryToken. Token will be invalidated on password change.

Params

  • token (string) - encrypted token generated via the temporary_token GraphQL property
  • user_id (numberstring) - id of the user who generated the token; a whole number, or a string holding one

Returns

boolean - returns true if the token has not expired and was generated for the given user, false otherwise

Examples


      {% assign token = '1234' %}
{{ token | is_token_valid: context.current_user.id }} => false
    

json (aliases: to_json)

Serializes the value as JSON

Params

  • object (untyped) - object you want a JSON representation of

Returns

string - JSON formatted string containing a representation of object.

Examples


      {{ user | json }} => {"name":"Mike","email":"[email protected]"}
    

jwe_encode (aliases: jwe_encode_rc)

Encrypts a JSON payload as a JWE token

Params

  • json (string) - JSON body string that will be encypted
  • key (string) - Public key
  • alg (string) - Key Management Algorithm used to encrypt, or to determine the value of, the Content Encryption Key Valid options: Single Asymmetric Public/Private Key Pair RSA1_5 RSA-OAEP RSA-OAEP-256 Two Asymmetric Public/Private Key Pairs with Key Agreement ECDH-ES ECDH-ES+A128KW ECDH-ES+A192KW ECDH-ES+A256KW Symmetric Password Based Key Derivation PBES2-HS256+A128KW PBES2-HS384+A192KW PBES2-HS512+A256KW Symmetric Key Wrap A128GCMKW A192GCMKW A256GCMKW A128KW A192KW A256KW Symmetric Direct Key (known to both sides) dir
  • enc (string) - Encryption Algorithm used to perform authenticated encryption on the plain text, using the Content Encryption Key Valid options: A128CBC-HS256 A192CBC-HS384 A256CBC-HS512 A128GCM A192GCM A256GCM

Returns

string

jwt_decode

Decodes a JWT and verifies its signature

Params

  • encoded_token (string) - encoded JWT token you want to decode
  • algorithm (string) - the algorithm that was used to encode the token
  • secret (string) - either a shared secret or a PUBLIC key for RSA - default: ''
  • verify_signature (boolean) - default true, for testing and debugging can remove verifying the signature - default: true
  • jwks (object) - JWK is a structure representing a cryptographic key. Currently only supports RSA public keys. Valid options: none - unsigned token HS256 - SHA-256 hash algorithm HS384 - SHA-384 hash algorithm HS512 - SHA-512 hash algorithm RS256 - RSA using SHA-256 hash algorithm RS384 - RSA using SHA-384 hash algorithm RS512 - RSA using SHA-512 hash algorithm - default: nil

Returns

untyped - result of decoding JWT token

Examples


      {% assign original_payload = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJrZXkiOiJ2YWx1ZSIsImFub3RoZXJfa2V5IjoiYW5vdGhlciB2YWx1ZSJ9.XT8sHXyPTA9DoHzssXh1q6Uv2D1ENosW0F3Ixle85L0' | jwt_decode: 'HS256', 'this-is-secret'  %} =>
[
  {
    "key" => "value",
    "another_key" => "another value"
  },
  {
    "typ" => "JWT",
    "alg" => "HS256"
  }
]
    

      RSA:
{% capture public_key %}
-----BEGIN PUBLIC KEY-----
MIIBI...
-----END PUBLIC KEY-----
{% endcapture %}
{% assign original_payload = 'some encoded token' | jwt_decode: 'RS256', public_key %}
    

jwt_encode

Encodes a payload as a signed JWT

Params

  • payload (object) - payload or message you want to encrypt
  • algorithm (string) - algorithm you want to use for encryption
  • secret (string) - either a shared secret or a private key for RSA - default: nil
  • header_fields (object) - optional hash of custom headers to be added to default { "typ": "JWT", "alg": "[algorithm]" } - default: {}

Keys other than these are accepted too.

Returns

string - JWT token encrypted using the algorithm of your choice

Examples


      {% assign payload = { "key": "value", "another_key": "another value" } %}
{{ payload | jwt_encode: 'HS256', 'this-is-secret' }} => eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJrZXkiOiJ2YWx1ZSIsImFub3RoZXJfa2V5IjoiYW5vdGhlciB2YWx1ZSJ9.XT8sHXyPTA9DoHzssXh1q6Uv2D1ENosW0F3Ixle85L0
    

      {% assign payload = { "key": "value", "another_key": "another value" } %}
{% assign headers = { "cty": "custom" } %}
{{ payload | jwt_encode: 'HS256', 'this-is-secret', headers }} => eyJjdHkiOiJjdXN0b20iLCJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJrZXkiOiJ2YWx1ZSIsImFub3RoZXJfa2V5IjoiYW5vdGhlciB2YWx1ZSJ9.DHizgDTArO7RpQE3124ufD9oirmQwrlftpxBwc9wGGA
    

      RSA:
{% capture private_key %}
-----BEGIN RSA PRIVATE KEY-----
MIIEpA...
-----END RSA PRIVATE KEY-----
{% endcapture %}
{% assign jwt_token = payload | jwt_encode: 'RS256', private_key  %}
{% comment %} Please note that storing private key as a plain text in a code is not a good idea. We suggest you
              provide the key via Partner Portal and use context.constants.<name of private key constant> instead.{% endcomment %}
    

      VAPID (RFC 8292) - EC keys are commonly generated outside the app (e.g. via the `web-push` CLI) and
distributed as a raw, Base64url-encoded private key scalar rather than PEM; that format is accepted
directly for ES256/ES384/ES512:
{% assign claims = '{"aud": "https://push-service.example.com", "exp": 1700000000, "sub": "mailto:[email protected]"}' | parse_json %}
{% assign vapid_jwt = claims | jwt_encode: 'ES256', vapid_private_key %}
    

l (aliases: localize)

Formats a time using a named format taken from the translations

Params

  • time (stringnumberdatetime) - parsable time object to be formatted; a number is read as whole seconds since the epoch, so a fractional one is refused
  • format (string) - the format to be used for formatting the time; default is 'long'; other values can be used: they are taken from translations, keys are of the form 'time.formats.#!{format_name}' - default: 'long'
  • zone (stringnumber) - the time zone to be used for time — a zone name, or a number read as its UTC offset in hours (in seconds when the magnitude is above 13) - default: nil

Returns

string - formatted representation of the passed parsable time, or nil

Examples


      {{ '2010-01-01' | l }} => Fri, Jan 1, 2010 at 12:00
    

      {{ 'in 14 days' | strftime: '%B %d, %Y', '', '2011-03-01' }} => March 15, 2011
    

map

Extracts the value of the given key from every object in the array

Params

  • object (array) - array of Hash to be processed. Nulls are skipped.
  • key (string) - name of the hash key for which all values should be returned in array of objects

Returns

array - array which includes all values for a given key

Examples


      {% assign objects = '[{"id":1,"name":"foo","label":"Foo"},{"id":2,"name":"bar","label":"Bar"}]' | parse_json %}
{{ objects | map: 'name' }} => ['foo', 'bar']
    

markdown (aliases: markdownify)

Converts Markdown into sanitized HTML

Params

  • text (string) - text using markdown syntax
  • options (objectstring) - sanitizer configuration, as a hash or as a string containing a JSON object. Replaces the default configuration entirely; pass `nil` to keep it and override only parts of it through `extra_options` - default: SANITIZE_DEFAULT
  • extra_options (objectstring) - the same configuration — a hash or a string containing a JSON object — deep-merged over `options` rather than replacing it, so one element or attribute can be changed without restating the rest. A key set to null removes it; a key set to an empty object empties it param; pass nil for the options param to use the default options which extra_options could then override. Unlike `options`, null is not accepted here: pass an empty object to override nothing - default: {}

Named options

  • elements (array) - Element names to keep; everything else is unwrapped
  • attributes (object) - Attribute names to keep per element, e.g. `{ "a": ["href"] }`; the key `all` applies to every element
  • protocols (object) - URL schemes to allow per element and attribute, e.g. `{ "a": { "href": ["http", "https"] } }`
  • add_attributes (object) - Attributes to add per element, e.g. `{ "a": { "rel": "nofollow" } }`
  • remove_contents (array) - Elements whose contents are dropped along with the element itself
  • allow_comments (boolean) - Keeps HTML comments instead of removing them (defaults to false)

Keys other than these are accepted too.

Returns

string - processed text with markdown syntax changed to sanitized HTML. We allow only safe tags and attributes by default. We also automatically add `rel=nofollow` to links. Default configuration is: { "elements": ["a","abbr","b","blockquote","br","cite","code","dd","dfn","dl","dt","em","i","h1","h2","h3","h4","h5","h6","img","kbd","li","mark","ol","p","pre","q","s","samp","small","strike","strong","sub","sup","time","u","ul","var"], "attributes":{ "a": ["href"], "abbr":["title"], "blockquote":["cite"], "img":["align","alt","border","height","src","srcset","width"], "dfn":["title"], "q":["cite"], "time":["datetime","pubdate"] }, "add_attributes": { "a" : {"rel":"nofollow"} }, "protocols": { "a":{"href":["ftp","http","https","mailto","relative"]}, "blockquote": {"cite": ["http","https","relative"] }, "q": {"cite": ["http","https","relative"] }, "img": {"src": ["http","https","relative"] } } }

Examples


      {{ '**Foo**' | markdown }} => <p><strong>Foo</strong></p>
    

      {{ '# Foo' | markdown }}  => '<h1>Foo</h1>'
    

      Automatically add rel=nofollow to links
{{ '[Foo link](https://example.com)' | markdown }}  => '<p><a href="https://example.com" rel="nofollow">Foo link</a></p>'
    

      {{ '<b>Foo</b>' | markdown }}  => '<b>Foo</b>'
    

      Tags not enabled by default are removed
{{ '<div class="hello" style="font-color: red; font-size: 99px;">Foo</div>' | markdown }}  => 'Foo'
    

      Attributes not enabled by default are removed
{% assign opts = '{ "elements": [ "div" ] }' %}
{{ '<div class="hello" style="font-color: red; font-size: 99px;">Foo</div>' | markdown: opts }} => <div>Foo</div>
    

      Specify custom tags with attributes
{% assign opts = '{ "elements": [ "div" ], "attributes": { "div": ["class"] } }' %}
{{ '<div class="hello" style="font-color: red; font-size: 99px;">Foo</div>' | markdown: opts }} => <div class="hello">Foo</div>
    

      Using extra_options to override options
{% assign link1 = '[Foo link](https://example.com)' | markdown: nil, '{ "add_attributes": { "a": { "custom_attr": "custom_value", "rel": null } } }' %}
{{ link1 }} => <p><a href="https://example.com" custom_attr="custom_value">Foo link</a></p>

{% assign link2 = '[Foo link](https://example.com)' | markdown: nil, '{ "add_attributes": { "a": {} } }' %}
{{ link2 }} => <p><a href="https://example.com">Foo link</a></p>

{% assign link3 = '[Foo link](https://example.com)' | markdown: nil, '{ "add_attributes": { "a": { "custom_attr": "custom_value" } } }' %}
{{ link3 }} => <p><a href="https://example.com" rel="nofollow" custom_attr="custom_value">Foo link</a></p>

{% assign link4 = '[Foo link](https://example.com)' | markdown %}
{{ link4 }} => <p><a href="https://example.com" rel="nofollow">Foo link</a></p>
    

matches

Checks whether the string matches the regular expression

Params

  • text (string) - string to check against the regular expression
  • regexp (string) - string representing a regular expression pattern against which
  • options (string) - can contain 'ixm'; i - ignore case, x - extended, m - multiline to match the first parameter - default: ''

Returns

boolean - whether the given string matches the given regular expression; returns null if

Examples


      {{ 'foo' | matches: '[a-z]' }} => true
    

pad_left

Pads the string from the left until it reaches the given length

Params

  • str (untyped) - string to pad; a non-string is stringified first
  • count (number) - minimum length of output string; must be a whole number
  • symbol (string) - string to pad with - default: ' '

Returns

string - returns string padded from left to the length of count with the symbol character

Examples


      {{ 'foo' | pad_left: 5 }} => '  foo'
    

      {{ 'Y' | pad_left: 3, 'X' }} => 'XXY'
    

parameterize

Replaces special characters so the string can be used as part of a URL

Params

  • text (string) - input string to be 'parameterized'
  • separator (string) - string to be used as separator in the output string; default is '-' - default: '-'

Returns

string - replaces special characters in a string so that it may be used as part of a 'pretty' URL; the default separator used is '-';

Examples


      {{ 'John arrived_foo' | parameterize }} => 'john-arrived_foo'
    

parse_csv (aliases: parse_csv_rc)

Parses a CSV string into rows

Params

  • input (string) - CSV
  • options (object) - parse csv options - default: {}

Named options

  • convert_to_hash (boolean) - Returns [Array of Objects]

Returns

array - Array

Examples


      {% capture csv %}name,description
name-1,description-1
name-2,description-2
{% endcapture %}
{{ csv | parse_csv }} => [["name","description"],["name-1","description-1"],["name-2","description-2"]]
{{ csv | parse_csv: convert_to_hash: true }} => [{"name":"name-1","description":"description-1"},{"name":"name-2","description":"description-2"}]
    

parse_xml (aliases: xml_to_hash)

Parses an XML string into a hash

Params

  • xml (string) - String containing valid XML
  • options (object) - attr_prefix: use '@' for element attributes, force_array: always try to use arrays for child elements - default: {}

Named options

  • attr_prefix (boolean) - Reads an element's attributes under keys prefixed with '@', telling them apart from child elements of the same name (defaults to false)
  • force_array (boolean) - Wraps every child element in an array, whether or not it repeats (defaults to true)

Returns

object - Hash created based on XML

Examples


      {% liquid
  assign text = '<?xml version="1.0" encoding="UTF-8"?><letter><title maxlength="10"> Quote Letter </title></letter>'
  assign object = text | parse_xml
%}
{{ object }} => '{"letter":[{"title":[{"maxlength":"10","content":" Quote Letter "}]}]}'
    

pluralize

Use either singular or plural version of a string, depending on provided count

Params

  • string (string) - string to be pluralized
  • count (number) - optional whole number based on which string will be pluralized or singularized - default: 2

Returns

string - pluralized version of the input string

Examples


      {{ 'dog' | pluralize: 1 }} => 'dog'
{{ 'dog' | pluralize: 2 }} => 'dogs'
    

pricify

Formats an amount as a price, with the currency symbol and thousands separators

Params

  • amount (numberstring) - amount to be formatted; a string holding a number and a money object are accepted too
  • currency (string) - currency to be used for formatting; optional, defaults to 'USD' - default: 'USD'
  • options (object) - optional Money formatting options; default no_cents_if_whole: true - default: {}

Named options

  • symbol (boolean) - Prints the currency symbol (defaults to the instance's "show currency symbol" setting)
  • with_currency (boolean) - Appends the currency name (defaults to the instance's "show currency name" setting)
  • no_cents_if_whole (boolean) - Drops the decimal part when the amount is whole (defaults to the instance's setting)
  • sign_before_symbol (boolean) - Puts a negative sign before the currency symbol rather than after it (defaults to true)

Keys other than these are accepted too.

Returns

string - formatted price using global price formatting rules

Examples


      {{ 0 | pricify }} => $0
    

      {{ 1 | pricify }} => $1
    

      {{ 1.20 | pricify }} => $1.20
    

      {{ 1000000 | pricify }} => $1,000,000
    

      {{ 1 | pricify: "PLN" }} => 1 zł
    

      {{ 1 | pricify: "JPY" }} => ¥1
    

      {{ 1 | pricify: "USD", no_cents_if_whole: false }} => $1.00
    

pricify_cents

Adds currency symbol and proper commas. It is used to showing prices to people.

Params

  • amount (numberstring) - amount in cents to be formatted; a string holding a number and a money object are accepted too
  • currency (string) - currency to be used for formatting - default: 'USD'
  • options (object) - optional Money formatting options; default no_cents_if_whole: true - default: {}

Named options

  • symbol (boolean) - Prints the currency symbol (defaults to the instance's "show currency symbol" setting)
  • with_currency (boolean) - Appends the currency name (defaults to the instance's "show currency name" setting)
  • no_cents_if_whole (boolean) - Drops the decimal part when the amount is whole (defaults to the instance's setting)
  • sign_before_symbol (boolean) - Puts a negative sign before the currency symbol rather than after it (defaults to true)

Keys other than these are accepted too.

Returns

string - formatted price using the global price formatting rules

Examples


      {{ 1 | pricify_cents }} => $0.01
    

      {{ 100 | pricify_cents }} => $1
    

      {{ 1000000 | pricify_cents }} => $10,000
    

      {{ 1 | pricify_cents: "PLN" }} => 0.01 zł
    

      {{ 1 | pricify_cents: "JPY" }} => ¥1
    

querify

Converts a hash into a URL query string

Params

  • hash (object) - hash to be "querified"

Returns

string - a query string

Examples


      {{ hash }} => { 'name' => 'Dan', 'id' => 1 }
    

      {{ hash | querify }} => 'name=Dan&id=1'
    

random_string

Generates a random alphanumeric string of the given length

Params

  • length (number) - how many random characters should be included; must be a whole number, default is 12 - default: 12

Returns

string - returns a random alphanumeric string of given length

Examples


      {{ 10 | random_string }} => '6a1ee2629'
    

raw_escape_string

HTML-escapes the string, so its tags are shown as text instead of being rendered

Params

  • value (untyped) - input string to be HTML-escaped; a non-string is stringified first

Returns

string - HTML-escaped input string; returns a string with its HTML tags visible in the browser

Examples


      {{ 'foo<b>bar</b>' | raw_escape_string }} => foo&lt;b&gt;bar&lt;/b&gt;
    

regex_matches

Returns every match of the regular expression in the string

Params

  • text (untyped) - string to search; a non-string is stringified first
  • regexp (string) - regexp to use for matching
  • options (string) - can contain 'ixm'; i - ignore case, x - extended, m # - multiline (e.g. 'ix', 'm', 'mi' etc.) - default: ''

Returns

array - matches for the expression in the string; each item in the array is an array containing all groups of matches; for example for the regex (.)(.) and the text 'abcdef', the result will look like: [["a", "b"], ["c", "d"], ["e", "f"]]

Examples


      To retrieve the URL from a meta tag see the example below:

{% liquid
  assign text = '<html><head><meta property="og:image" content="http://somehost.com/someimage.jpg" /></head><body>content</body></html>' | html_safe
  assign matches = text | regex_matches: '<meta\s+property="og:image"\s+content="([^"]+)"'
  if matches.size > 0
    assign image_path = matches[0][0]
    echo image_path
  endif
%}
    

replace_regex

Replaces the parts of the string matching the regular expression

Params

  • text (string) - string to search and replace in
  • regexp (string) - regexp to use for matching
  • replacement (stringobject) - replacement text, or hash; if hash, keys in the hash must be matched texts and values their replacements
  • options (string) - can contain 'ixm'; i - ignore case, x - extended, m # - multiline (e.g. 'ix', 'm', 'mi' etc.) - default: ''
  • global (boolean) - whether all occurrences should be replaced or just the first - default: true

Returns

string - string with regexp pattern replaced by replacement text

Examples


      Basic example:
{{ "fooooo fooo" | replace_regex: 'o+', 'o' }} => "fo fo"
    

      Global set to false:
{{ "fooooo fooo" | replace_regex: 'o+', 'o', '', false }} => "fo fooo"
    

      Hash replacement:
{% liquid
  assign hash = {}
  assign hash = hash | hash_add_key: 'ooooo', 'bbbbb'
  assign hash = hash | hash_add_key: 'ooo', 'ccc'
  %}
{{ "fooooo fooo" | replace_regex: 'o+', hash }} => "fbbbbb fccc"
    

      Using options, ignore case:
{{ "FOOOOO" | replace_regex: 'o+', 'a', 'i' }} => "Fa"
{{ "FOOOOO" | replace_regex: 'o+', 'a' }} => "FOOOOO"
Using options, extended mode (insert spaces, newlines, and comments in the pattern to make it more readable):
{{ "FOOOOO" | replace_regex: 'o+ #comment', 'a', 'ix' }} => "Fa"
Using options, multiline (. matches newline):
{% capture newLine %}
{% endcapture %}
{{ "abc" | append: newLine | append: "def" | append: newLine | append: "ghi" | replace_regex: '.+', 'a', 'im' }} => "a"
    

      Matches group:
{% assign array = "item 1,item 2,item 3,item 4" | split: "," %}
{{ array | join: ", " | replace_regex: "([^,]+),([^,]+)$", "\1, &\2" }} => item 1, item 2, item 3, & item 4
    

sanitize

Removes the HTML elements and attributes that are not allowed

Params

  • input (string) - potential malicious html, which you would like to sanitize
  • options (objectstringarray) - options to configure which elements and attributes are allowed, example: { "elements": ["a", "b", "h1"], "attributes": { "a": ["href"] } }. A hash, or a string containing a JSON object; an array is read as the deprecated `whitelist_tags` form, an array of element names - default: SANITIZE_DEFAULT
  • whitelist_tags (array) - deprecated; do not use - default: nil

Named options

  • elements (array) - Element names to keep; everything else is unwrapped
  • attributes (object) - Attribute names to keep per element, e.g. `{ "a": ["href"] }`; the key `all` applies to every element
  • protocols (object) - URL schemes to allow per element and attribute, e.g. `{ "a": { "href": ["http", "https"] } }`
  • add_attributes (object) - Attributes to add per element, e.g. `{ "a": { "rel": "nofollow" } }`
  • remove_contents (array) - Elements whose contents are dropped along with the element itself
  • allow_comments (boolean) - Keeps HTML comments instead of removing them (defaults to false)

Keys other than these are accepted too.

Returns

string - Sanitizes HTML input. If you want to allow any HTML, use html_safe filter. By default we allow only safe html tags and attributes. We also automatically add `rel=nofollow` to links. Default configuration is: { "elements": ["a","abbr","b","blockquote","br","cite","code","dd","dfn","dl","dt","em","i","h1","h2","h3","h4","h5","h6","img","kbd","li","mark","ol","p","pre","q","s","samp","small","strike","strong","sub","sup","time","u","ul","var"], "attributes":{ "a": ["href"], "abbr":["title"], "blockquote":["cite"], "img":["align","alt","border","height","src","srcset","width"], "dfn":["title"], "q":["cite"], "time":["datetime","pubdate"] }, "add_attributes": { "a" : {"rel":"nofollow"} }, "protocols": { "a":{"href":["ftp","http","https","mailto","relative"]}, "blockquote": {"cite": ["http","https","relative"] }, "q": {"cite": ["http","https","relative"] }, "img": {"src": ["http","https","relative"] } } }

Examples


      {% capture link %}
  <a href="javascript:prompt(1)">Link</a>
{% endcapture %}
{{ link | sanitize }} => <a href="">Link</a>
{% assign whitelist_attributes = 'target' | split: '|' %}
{{ link | sanitize: whitelist_attributes }} => <a href="">Link</a>
    

scrub

Scrubs invalid characters and sequences from the input string, in the given encoding (by default UTF-8)

Params

  • text (untyped) - string to be scrubbed; a non-string is stringified first
  • source_encoding (string) - encoding of the input string, default UTF-8 - default: "UTF-8"
  • final_encoding (string) - encoding of the output string, default UTF-8 - default: "UTF-8"

Returns

string - Returns a string scrubbed of invalid characters and sequences; to be used when data is coming from external sources like APIs etc.

Examples


      {% assign scrubbed = "Hello W�orld" | scrub %}
{{ scrubbed }} => "Hello World"
    

slugify

Converts the string into a lowercase, dash-separated slug for use in a URL

Params

  • text (string) - input string to be 'slugified'

Returns

string - replaces special characters in a string so that it may be used as part of a 'pretty' URL;

Examples


      {{ 'John arrived_foo' | slugify }} => 'john-arrived-foo'
    

split

Splits a string into an array by the given separator; an Array passes through unchanged, so splitting a value twice is safe

Params

  • input (untyped) - value to split; an Array is returned unchanged
  • pattern (untyped) - separator to split the string by; a non-string is stringified first

Returns

array - array of substrings; if input is already an Array it is returned as-is

Examples


      {% assign array = 'a,b,c' | split: ',' %}
{{ array | split: ',' }} => ['a', 'b', 'c']
    

start_with

Check if string starts with given substring(s)

Params

  • string (string) - string to check if starts with any of the provided prefixes
  • prefixes (stringarray) - prefix to check, or an array of prefixes of which any one matching is enough

Returns

boolean - true if string starts with a prefix

Examples


      {{ 'my_example' | start_with: 'my' }} => true
    

      {{ 'my_example' | start_with: 'example' }} => false
    

      {% assign prefixes = ["array", "example"] %}
{{ 'my_example' | start_with: prefixes }} => false
    

strftime

Formats a time using a strftime format string

Params

  • time (stringnumberdatetime) - parsable time object; a number is read as whole seconds since the epoch
  • format (string) - string representing the desired output format e.g. '%Y-%m-%d' will result in '2020-12-21' Cheatsheet: https://devhints.io/strftime
  • zone (stringnumber) - string representing the time zone, or a number read as its UTC offset in hours (in seconds when the magnitude is above 13) - default: nil
  • now (stringnumberdatetime) - sets the time from which operation should be performed - default: nil

Returns

string - formatted representation of the time object; the formatted representation will be based on what the format parameter specifies

Examples


      {{ '2018-05-30T09:12:34.000-07:00' | strftime: '%Y-%m-%d %H:%M' }} => 2018-05-30 16:12 # no zone given, so the instance default applies; UTC here
    

      {% assign time = '2010-01-01 08:00' | to_time %}
{{ time | strftime: "%Y-%m-%d" }} => '2010-01-01'
    

      {{ '2018-05-30T09:12:34.000-07:00' | strftime: '%Y-%m-%d %H:%M', 'Europe/Warsaw' }} => 2018-05-30 18:12
{{ '2018-05-30T09:12:34.000-07:00' | strftime: '%Y-%m-%d %H:%M', 'America/New_York' }} => 2018-05-30 12:12
{{ '2018-05-30T09:12:34.000-07:00' | strftime: '%Y-%m-%d %H:%M', 'Sydney' }} => 2018-05-31 02:12
{{ '2018-05-30T09:12:34.000-07:00' | strftime: '%Y-%m-%d %H:%M', 'Pacific/Apia' }} => 2018-05-31 05:12
    

strip_liquid

Removes Liquid tags from the text, keeping the content they wrap

Params

  • text (string) - text from which to strip liquid

Returns

string - input parameter without liquid

Examples


      {% capture text %}Hello! {% raw %}{% comment %}This is a comment!{% endcomment %}{% endraw %}{% endcapture %}
{{ text | strip_liquid }} => Hello! This is a comment!
    

t (aliases: translate)

Looks up a translation by key

Params

  • key (string) - translation key
  • options (object) - values passed to translation string - default: {}

Named options

  • locale (string) - Enforces using specified locale instead of value provided via `?language=<locale>`
  • default (string) - Specifies the default for a scenario when translation is missing. If fallback not set to true, system will automatically try to load english translation first
  • fallback (boolean) - specify whether the system should try to fallback to english if translation is missing for the current locale
  • scope (string) - Looks the key up under this prefix, so `t: scope: 'drinks.alcoholic'` resolves `beer` as `drinks.alcoholic.beer`
  • count (number) - Selects the plural form of the translation, and is interpolated as `%{count}`

Keys other than these are accepted too.

Returns

untyped - Translation value taken from translations YML file for the key given as parameter. The value is assumed to be html safe, please use `t_escape` if you provide unsafe argument which can potentially include malicious script.

Examples


      {{ 'beer' | t }} => 'cerveza'
    

      {{ 'drinks.alcoholic.beer' | t }} => 'piwo'
    

      {{ 'non_existing_translation' | t: default: 'Missing', fallback: false }} => 'Missing'
    

      {{ 'user-greeting' | t: username: 'Mike' }} => 'Hello Mike!'
    

t_escape (aliases: translate_escape)

Escapes unsafe arguments passed to the translation and then returns its value

Params

  • key (string) - translation key
  • options (object) - values passed to translation string - default: {}

Named options

  • locale (string) - Enforces using specified locale instead of value provided via `?language=<locale>`
  • default (string) - Specifies the default for a scenario when translation is missing
  • fallback (boolean) - specify whether the system should try to fallback to english if translation is missing
  • scope (string) - Looks the key up under this prefix
  • count (number) - Selects the plural form of the translation, and is interpolated as `%{count}`

Keys other than these are accepted too.

Returns

untyped - translation value taken from translations YML file for the key given as parameter

Examples


      en.yml
en:
  user-greeting: Hello %{username}

{{ 'user-greeting' | t_escape: username: '<script>alert("hello")</script>Mike' }}
=> will not evaluate the script, it will print out:
Hello <script>alert("hello")</script>Mike
    

time_diff

Returns the duration between two times, in the given unit

Params

  • start (stringnumberdatetime) - time the duration is measured from; a number is read as whole seconds since the epoch
  • finish (stringnumberdatetime) - time the duration is measured to
  • unit (string) - time unit - allowed options are: d, days, h, hours, m, minutes, s, seconds, ms, milliseconds [default]; anything else falls back to milliseconds - default: 'ms'
  • precision (number) - defines rounding after comma; must be a whole number, default is 3 - default: 3

Returns

number - duration between start and finish in unit; default is ms (milliseconds)

Examples


      {% assign result = 'now' | time_diff: 'in 5 minutes', 'd' %}
{{ result }}
    

      {% assign minutes_until_date = 'now' | time_diff: '2026-10-08 00:00', 'm' %}
{% comment %}{% background _ = 'commands/foo', delay: minutes_until_date %} %}{% endcomment %}
    

titleize

Capitalizes every word of the string, replacing underscores and dashes with spaces

Params

  • text (untyped) - string to be processed; a non-string is stringified first

Returns

string - capitalizes all the words and replaces some characters in the string to create a string in title-case format

Examples


      {{ 'foo bar_zoo-xx' | titleize }} => 'Foo Bar Zoo Xx'
    

to_csv

Converts an array of rows into a CSV string

Params

  • input (array) - array of rows you would like to convert to CSV; every element must itself be an array
  • options (object) - csv options - default: {}

Named options

  • row_sep (string) - Specifies the row separator; used to delimit rows.
  • col_sep (string) - Specifies the column separator; used to delimit fields.
  • quote_char (string) - Specifies the quote character; used to quote fields.
  • write_headers (boolean) - Specifies whether headers are to be written.
  • force_quotes (boolean) - Specifies whether each output field is to be quoted.
  • quote_empty (boolean) - Specifies whether each empty output field is to be quoted.
  • sanitize (boolean) - Escape special chars to prevent CSV injection attacks, default true.

Keys other than these are accepted too.

Returns

string - String containing CSV. If one of the array element contains separator, this element will automatically be wrapped in double quotes.

Examples


      {% liquid
  assign arr = '' | split: ','
  assign headers = 'id,header1,header2' | split: ','
  assign row1 = '1,example,value' | split: ','
  assign row2 = '2,another,val2' | split: ','
  assign arr = arr | array_add: headers | array_add: row1 | array_add: row2
%}
{{ arr | to_csv }} => "id","header1","header2"\n1,"example","value"\n2,"another","val2"
    

      {{ arr | to_csv: force_quotes: true }} => "id","header1","header2"\n"1","example","value"\n"2","another","val2"
    

to_date

Parses the input into a date

Params

  • time (stringnumberdatetime) - parsable time object to be converted to date; a number is read as whole seconds since the epoch

Returns

date - a Date object obtained/parsed from the input object

Examples


      {{ '2010-01-01 8:00:00' | to_date }} => 2010-01-01
    

to_mobile_number

Formats a phone number in E.164 format, for sending SMS notifications

Params

  • number (string) - the base part of mobile number
  • country (string) - country for which country code should be used. Can be anything - full name, iso2, iso3 - default: nil

Returns

string - returns mobile number in E.164 format; recommended for sending sms notifications

Examples


      {{ '500 123 999' | to_mobile_number: 'PL' }} => '+48500123999'
    

to_positive_integer

Coerces the value to a positive integer, falling back to the given default

Params

  • param (untyped) - value to be coerced to positive integer
  • default (number) - default value in case param is not valid positive integer; must be a whole number

Returns

number - number that is higher than 0

Examples


      {{ '1' | to_positive_integer: 2 }} => 1
{{ '' | to_positive_integer: 2 }} => 2
    

to_time

Parses the input into a time, accepting natural language such as 'in 3 days'

Params

  • time (stringnumberdatetime) - a string representation of time ('today', '3 days ago', 'in 10 minutes' etc.), a whole number in UNIX time format, or a time
  • zone (stringnumber) - time zone — a zone name, or a number read as its UTC offset in hours (in seconds when the magnitude is above 13) - default: nil
  • format (string) - specific format to be used when parsing time - default: nil
  • now (stringnumberdatetime) - sets the time from which operation should be performed - default: nil

Returns

time - a time object created from parsing the string representation of time given as input

Examples


      {% comment %}The outputs below are relative to the time of rendering. They are shown
against one fixed reference, 2017-04-15 15:21:00, so the offsets can be compared.
{% endcomment %}
{{ 'today' | to_time }} => 2017-04-15 15:21:00
    

      {{ 'today' | to_time: 'UTC' }} => 2017-04-15 15:21:00
    

      {{ '1 day ago' | to_time }} => 2017-04-14 15:21:00
    

      {{ '5 days from now' | to_time }} => 2017-04-19 15:21:00
    

      {{ '2010:01:01' | to_time: '', '%Y:%m:%d' }} => 2010-01-01 00:00:00
    

      {{ '5 days from now' | to_time: '', '', '2019-10-01' }} => 2019-10-06 12:00:00 UTC # equivalent of {{ '2019-10-01' | add_to_time: 5, 'days' }}
    

to_xml (aliases: to_xml_rc)

Serializes a hash as XML

Params

  • object (objectarray) - hash object that will be represented as xml; an array is written as a series of `<anon>` elements
  • options (object) - attr_prefix: use '@' for element attributes - default: {}

Named options

  • attr_prefix (boolean) - Writes keys beginning with '@' as element attributes rather than as child elements (defaults to false)

Returns

string - String containing XML

Examples


      {% liquid
  assign object = '{"letter":[{"title":[{"maxlength":"10","content":" Quote Letter "}]}]}' | parse_json
  assign xml = object | to_xml
%}
{{ object }} => '<letter> <title maxlength="10"> Quote Letter </title> </letter>'
    

type_of

Returns the name of the value's type

Params

  • variable (untyped) - Variable whose type you want returned

Returns

string - Type of the variable parameter

Examples


      {% assign variable_type = '{ "name": "foo", "bar": {} }' | parse_json | type_of %}
{{ variable_type }}
    

unescape_javascript

Reverses escape_javascript, returning the text to its original form

Params

  • text (string) - text to be unescaped

Returns

string - unescaped javascript text

Examples


      {% capture js %}
<script>
  let variable = "\t some text\n";
  let variable2 = 'some text 2';
  let variable3 = `some text`;
  let variable4 = `We love ${variable3}.`;
  </script>
{% endcapture %}

This will return the text to its original form:
{{ js | escape_javascript | unescape_javascript }}
    

url_to_qrcode_svg

Renders the URL as a QR code in SVG

Params

  • url (string) - URL to be encoded as QR code
  • options (object) - optional. Defaults: color: "000", module_size: 11, shape_rendering: "crispEdges", viewbox: false - default: {}

Named options

  • shape_rendering (string) - Possible options: auto | optimizeSpeed | crispEdges | geometricPrecision ; default is crispEdges
  • viewbox (boolean) - Replace the `svg.width` and `svg.height` attribute with `svg.viewBox` to allow CSS scaling , default false
  • standalone (boolean) - Whether to make this a full SVG file, or only an svg to embed in other svg, default true
  • svg_attributes (object) - An optional hash of custom <svg> attributes. Existing attributes will remain. (default {})
  • color (string) - Default is "000"
  • module_size (number) - Default is 11

Returns

string - either `<path ...>...</path>` or `<svg ...>...</svg>` depending on standalone flag

Examples


      <svg width="319" height="319">{{ 'https://example.com' | url_to_qrcode_svg: color: '000', module_size: 11 }}</svg>
    

useragent

Parses a user agent header into browser, engine, OS and device information

Params

  • useragent_header (string) - browser user agent from the request header

Returns

object - parsed browser user agent information

Examples


      {{ context.headers.HTTP_USER_AGENT | useragent }} =>
{
  "device": {"family":"Other","model":"Other","brand":null},
  "family":"Firefox",
  "os":{"version":null,"family":"Windows 7"},
  "version":{"version":"47.0","major":"47","minor":"0","patch":null}
}
    

uuid

Generates a random universally unique identifier (UUID v4)

Params

  • _dummy (untyped) - parameter will be ignored - default: nil

Returns

string - Universally unique identifier v4

Examples


      {{ '' | uuid }} => "2d931510-d99f-494a-8c67-87feb05e1594"

{% assign id = '' | uuid %}
{{ id }} => "b12bd15e-4da7-41a7-b673-272221049c01"
    

verify_access_key

Checks whether the given Partner Portal access key is valid

Params

  • access_key (untyped) - can be obtained in Partner Portal; anything but a hash is looked up as written, and a value that is not a key is simply false

Returns

boolean - check if key is valid

Examples


      {% assign access_key = '12345' %}
{{ access_key | verify_access_key }} => true
    

video_params

Extracts provider, video id and embed metadata from a video URL

Params

  • url (string) - URL to a video on the internet

Returns

object - metadata about video

Examples


      {{ 'https://www.youtube.com/watch?v=8N_tupPBtWQ' | video_params }}
{% comment %}
  Returns a Hash with the keys: provider ("YouTube"), url (the input), video_id
  ("8N_tupPBtWQ"), embed_url ("https://www.youtube.com/embed/8N_tupPBtWQ") and
  embed_code (an iframe element wrapping embed_url).
{% endcomment %}
    

videoify

Turns a video URL into an embedded video player

Params

  • url (string) - URL to a video on the internet - default: ''
  • options (object) - optional HTML attributes for the generated iframe (e.g. width, height) - default: {}

Keys other than these are accepted too.

Returns

string - if the given URL is supported, an HTML formatted string containing a video player (inside an iframe) which will play the video at the given URL; otherwise an empty string is returned

www_form_encode (aliases: www_form_encode_rc)

Encodes the object as application/x-www-form-urlencoded data

Params

  • object (objectarray) - data object

Returns

string - This generates application/x-www-form-urlencoded data defined in HTML5 from given object.

Examples


      assign object = '{"foo": "bar", "zoo": [{ "xoo": 1 }, {"xoo": 2}]}' | parse_json
assign form_data = object | www_form_encode
  => "foo=bar&zoo[0][xoo]=555&zoo[1][xoo]=999",
    

add_hash_key

Returns the hash with the given key set to the given value

Params

  • hash (object) - hash to add the key to
  • key (untyped) - key to add; usually a string, but any value can be a key
  • value (untyped) - value to store under the key

Returns

object - hash with added key

Examples


      {% liquid
  assign accountants = "Angela,Kevin,Oscar" | split: ","
  assign management = "David,Jan,Michael" | split: ","
  assign company = {}
  assign company = company | hash_add_key: "name", "Dunder Mifflin"
  assign company = company | hash_add_key: "accountants", accountants
  assign company = company | hash_add_key: "management", management
%}
{{ company }} => {"name" => "Dunder Mifflin", "accountants" => ["Angela", "Kevin", "Oscar"], "management" => ["David", "Jan", "Michael"]}
    

add_to_array

Appends an element to the end of the array

Params

  • array (array) - array to which you add a new element
  • item (untyped) - item you add to the array

Returns

array - array to which you add the item given as the second parameter

Examples


      {% assign array = 'a,b,c' | split: ',' %}
{{ array | array_add: 'd' }} => ['a', 'b', 'c', 'd']
    

add_to_date

Adds a number of time units to a date

Params

  • time (stringnumberdatetime) - parsable time the units are added to; a number is read as whole seconds since the epoch
  • number (numberstring) - how many units to add — a string holding a number is accepted and a fractional number is truncated; optional, defaults to 1 - default: 1
  • unit (string) - time unit - allowed options are: y, years, mo, months, w, weeks, d [default], days, h, hours, m, minutes, s, seconds - default: 'd'

Returns

date - modified Date

Examples


      {{ '2010-01-01' | date_add: 1 }} => 2010-01-02
{{ '2010-01-01' | date_add: 1, 'mo' }} => 2010-02-01
    

any

Checks whether the array contains at least one element equal to the query

Params

  • array (array) - array to search in - default: []
  • query (untyped) - value compared to each item in the given array - default: 'true'

Returns

boolean - checks if given array contains at least one of the queried string/number

Examples


      {% assign elements = 'foo,bar' | split: ',' %}
{{ elements | array_any: 'foo' }} => true
    

array_include (aliases: is_included_in_array)

Checks if array includes element

Params

  • array (array) - array of elements to look into
  • el (untyped) - look for this element inside the array

Returns

boolean - whether the array includes the element given

Examples


      {% assign elements = 'a,b,c,d' | split: ',' %}
{{ elements | array_include: 'c' }} => true
    

asset_name_to_raw_url

Looks up an asset by name and returns the value stored in its `raw_url` column. Intended for migrating legacy data where an explicit URL was persisted on the asset row; new code should derive URLs from the asset name via `asset_url`.

Params

  • name (string) - asset name to look up

Returns

string - the asset's `raw_url` if the asset exists, nil otherwise

Examples


      {{ 'logo.png' | asset_name_to_raw_url }} => 'https://example.com/instances/1/assets/logo.png'
    

asset_path

Generates relative path to an asset, including `updated` query parameter. The `/assets/` prefix is rewritten to the CDN origin by the reverse proxy at request time, so the rendered HTML stays portable across environments (custom domains, previews, on-prem). Always prefer `asset_url`, which points clients straight at the CDN — `asset_path` forces every request through the regional load balancer and reverse proxy before the CDN is reached, which defeats most of the CDN's benefit.

Params

  • file_path (string) - path to the asset, relative to assets directory

Returns

string - relative path to the physical file decorated with updated param to invalidate CDN cache.

Examples


      {{ "valid/file.jpg" | asset_path }} => /assets/valid/file.jpg?updated=1565632488
    

assign_to_hash_key

Returns the hash with the given key set to the given value

Params

  • hash (object) - hash to add the key to
  • key (untyped) - key to add; usually a string, but any value can be a key
  • value (untyped) - value to store under the key

Returns

object - hash with added key

Examples


      {% liquid
  assign accountants = "Angela,Kevin,Oscar" | split: ","
  assign management = "David,Jan,Michael" | split: ","
  assign company = {}
  assign company = company | hash_add_key: "name", "Dunder Mifflin"
  assign company = company | hash_add_key: "accountants", accountants
  assign company = company | hash_add_key: "management", management
%}
{{ company }} => {"name" => "Dunder Mifflin", "accountants" => ["Angela", "Kevin", "Oscar"], "management" => ["David", "Jan", "Michael"]}
    

compact

Removes blank elements from the array

Params

  • array (array) - array with some blank values
  • property (string) - optionally if you provide Hash as argument, you can remove elements which given key is blank - default: nil

Returns

array - array from which blank values are removed

Examples


      {{ '1,' | split: ',' | array_add: false | array_add: '2' | array_compact }} => ["1","2"]
    

      {{ '1,' | split: ',' | array_add: null | array_add: '2' | array_compact }} => ["1","2"]
    

      {% assign empty_object = {} %}
{{ '1,' | split: ',' | array_add: empty_object | array_add: '2' | array_compact }} => ["1","2"]
    

      {% assign empty_array = ',' | split: ',' %}
{{ '1,' | split: ',' | array_add: empty_array | array_add: '2' | array_compact }} => ["1","2"]
    

      {% assign hash = [{ "hello": null }, { "hello": "world" }, { "hello": "" }] %}
{{ hash | array_compact: "hello" }} => [{"hello":"world"}]
    

date_before

Checks whether the first time is earlier than the second

Params

  • first_time (stringnumberdatetime) - time to compare to the second parameter; a number is read as whole seconds since the epoch
  • second_time (stringnumberdatetime) - time against which the first parameter is compared to

Returns

boolean - returns true if the first time is lower than the second time

Examples


      {{ '2010-01-02' | date_before: '2010-01-03' }} => true
    

      {{ '6 months ago' | date_before: '2010-01-03' }} => false
    

      {{ '1 day ago' | date_before: 'now' }} => true
    

delete_hash_key

Removes the given key from the hash and returns the value it held

Params

  • hash (object) - hash to remove the key from
  • key (string) - key to remove

Returns

untyped - value which was assigned to a deleted key. If the key did not exist in the first place, null is returned.

Examples


      {% liquid
  assign hash = '{ "a": "1", "b": "2"}' | parse_json
  assign a_value = hash | hash_delete_key: "a"
%}
{{ a_value }} => "1"
{{ hash }} => { "b": "2" }
    

detect

Returns the first element matching all the given field conditions

Params

  • objects (array) - array of objects to be processed
  • conditions (object) - hash with conditions { field_name: value } - default: {}

Keys other than these are accepted too.

Returns

untyped - first object from the collection that matches the specified conditions

Examples


      {{ objects }} => [{"foo":1,"bar":"a"},{"foo":2,"bar":"b"},{"foo":3,"bar":"c"}]
{{ objects | array_detect: foo: 2 }} => {"foo":2,"bar":"b"}
    

dig

Extracts a nested value by following the given sequence of keys

Params

  • hash (object) - hash to traverse
  • keys (array) - comma separated sequence of keys to dig down the hash; a key is a string, or a whole number where the value being stepped into is an array — `hash_dig: 'images', 0, 'url'`

Returns

untyped - Extracted nested value specified by the sequence of keys by calling dig at each step, returning null if any intermediate step is null.

Examples


      {% assign user_json = { "name": { "first": "John", "last": "Doe" } } %}
{{ user_json | hash_dig: "name", "first" }} => John
    

fetch

Reads a single key from the hash

Params

  • hash (object) - input hash to be traversed
  • key (string) - key to be fetched from hash branch

Returns

untyped

Examples


      {% assign users = [{ "name": "Jane" }, { "name": "Bob" }] %}
{{ users | first | hash_fetch: "name" }} => Jane
    

flatten

Flattens an array of arrays into a single array

Params

  • array (array) - array of arrays to be processed

Returns

array - with objects

Examples


      {{ array_of_arrays }} => [[1,2], [3,4], [5,6]]
{{ array_of_arrays | array_flatten }} => [1,2,3,4,5,6]
    

group_by

Transforms array into hash, with keys equal to the values of object's method name and value being array containing objects

Params

  • objects (array) - array to be grouped
  • method_name (string) - method name to be used to group Objects

Returns

object - the original array grouped by method specified by the second parameter

Examples


      {% assign objects = [
  { "size": "xl", "color": "red" },
  { "size": "xl", "color": "yellow" },
  { "size": "s", "color": "red" }
] %}
{{ objects | array_group_by: 'size' }} => {"xl":[{"size":"xl","color":"red"},{"size":"xl","color":"yellow"}],"s":[{"size":"s","color":"red"}]}
    

hash_fetch (aliases: fetch)

Reads a single key from the hash

Params

  • hash (object) - input hash to be traversed
  • key (string) - key to be fetched from hash branch

Returns

untyped

Examples


      {% assign users = [{ "name": "Jane" }, { "name": "Bob" }] %}
{{ users | first | hash_fetch: "name" }} => Jane
    

in_groups_of

Transforms array in array of arrays, each subarray containing exactly N elements

Params

  • array (array) - array to be split into groups
  • number_of_elements (number) - the size of each group the array is to be split into; must be a whole number

Returns

array - the original array split into groups of the size specified by the second parameter (an array of arrays)

Examples


      {% assign elements = '1,2,3,4' | split: ',' %}
{{ elements | array_in_groups_of: 3 }} => [[1, 2, 3], [4, null, null]]
    

intersection

Returns the elements present in both arrays

Params

  • array (array) - array of objects to be processed
  • other_array (array) - array of objects to be processed

Returns

array - that exists in both arrays

Examples


      {% liquid
  assign array = '1,2,3,4' | split: ','
  assign other_array = '3,4,5,6' | split: ','
%}

{{ array | array_intersect: other_array }} => [3,4]
    

is_included_in_array

Checks if array includes element

Params

  • array (array) - array of elements to look into
  • el (untyped) - look for this element inside the array

Returns

boolean - whether the array includes the element given

Examples


      {% assign elements = 'a,b,c,d' | split: ',' %}
{{ elements | array_include: 'c' }} => true
    

jwe_encode_rc

Encrypts a JSON payload as a JWE token

Params

  • json (string) - JSON body string that will be encypted
  • key (string) - Public key
  • alg (string) - Key Management Algorithm used to encrypt, or to determine the value of, the Content Encryption Key Valid options: Single Asymmetric Public/Private Key Pair RSA1_5 RSA-OAEP RSA-OAEP-256 Two Asymmetric Public/Private Key Pairs with Key Agreement ECDH-ES ECDH-ES+A128KW ECDH-ES+A192KW ECDH-ES+A256KW Symmetric Password Based Key Derivation PBES2-HS256+A128KW PBES2-HS384+A192KW PBES2-HS512+A256KW Symmetric Key Wrap A128GCMKW A192GCMKW A256GCMKW A128KW A192KW A256KW Symmetric Direct Key (known to both sides) dir
  • enc (string) - Encryption Algorithm used to perform authenticated encryption on the plain text, using the Content Encryption Key Valid options: A128CBC-HS256 A192CBC-HS384 A256CBC-HS512 A128GCM A192GCM A256GCM

Returns

string

limit

Returns at most the first N elements of the array

Params

  • array (array) - array to shrink
  • limit (number) - number of elements to be returned; must be a positive integer

Returns

array - the first `limit` elements; [1,2,3,4] limited to 2 elements gives [1,2]

Examples


      items => [{ id: 1, name: 'foo', label: 'Foo' }, { id: 2, name: 'bar', label: 'Bar' }]
{{ items | array_limit: 1 }} => [{ id: 1, name: 'foo', label: 'Foo' }]
    

localize

Formats a time using a named format taken from the translations

Params

  • time (stringnumberdatetime) - parsable time object to be formatted; a number is read as whole seconds since the epoch, so a fractional one is refused
  • format (string) - the format to be used for formatting the time; default is 'long'; other values can be used: they are taken from translations, keys are of the form 'time.formats.#!{format_name}' - default: 'long'
  • zone (stringnumber) - the time zone to be used for time — a zone name, or a number read as its UTC offset in hours (in seconds when the magnitude is above 13) - default: nil

Returns

string - formatted representation of the passed parsable time, or nil

Examples


      {{ '2010-01-01' | l }} => Fri, Jan 1, 2010 at 12:00
    

      {{ 'in 14 days' | strftime: '%B %d, %Y', '', '2011-03-01' }} => March 15, 2011
    

map_attributes

Extracts the values of the given keys from every object in the array

Params

  • array (array) - array of objects to be processed
  • attributes (array) - array of keys to be extracted; a key is a string for an array of hashes, or a whole number index for an array of arrays

Returns

array - array of arrays with values for given keys

Examples


      {{ items }} => [{ id: 1, name: 'foo', label: 'Foo' }, { id: 2, name: 'bar', label: 'Bar' }]
{{ items | array_map: 'id', 'name' }} => [[1, 'foo'], [2, 'bar']]
    

markdownify

Converts Markdown into sanitized HTML

Params

  • text (string) - text using markdown syntax
  • options (objectstring) - sanitizer configuration, as a hash or as a string containing a JSON object. Replaces the default configuration entirely; pass `nil` to keep it and override only parts of it through `extra_options` - default: SANITIZE_DEFAULT
  • extra_options (objectstring) - the same configuration — a hash or a string containing a JSON object — deep-merged over `options` rather than replacing it, so one element or attribute can be changed without restating the rest. A key set to null removes it; a key set to an empty object empties it param; pass nil for the options param to use the default options which extra_options could then override. Unlike `options`, null is not accepted here: pass an empty object to override nothing - default: {}

Named options

  • elements (array) - Element names to keep; everything else is unwrapped
  • attributes (object) - Attribute names to keep per element, e.g. `{ "a": ["href"] }`; the key `all` applies to every element
  • protocols (object) - URL schemes to allow per element and attribute, e.g. `{ "a": { "href": ["http", "https"] } }`
  • add_attributes (object) - Attributes to add per element, e.g. `{ "a": { "rel": "nofollow" } }`
  • remove_contents (array) - Elements whose contents are dropped along with the element itself
  • allow_comments (boolean) - Keeps HTML comments instead of removing them (defaults to false)

Keys other than these are accepted too.

Returns

string - processed text with markdown syntax changed to sanitized HTML. We allow only safe tags and attributes by default. We also automatically add `rel=nofollow` to links. Default configuration is: { "elements": ["a","abbr","b","blockquote","br","cite","code","dd","dfn","dl","dt","em","i","h1","h2","h3","h4","h5","h6","img","kbd","li","mark","ol","p","pre","q","s","samp","small","strike","strong","sub","sup","time","u","ul","var"], "attributes":{ "a": ["href"], "abbr":["title"], "blockquote":["cite"], "img":["align","alt","border","height","src","srcset","width"], "dfn":["title"], "q":["cite"], "time":["datetime","pubdate"] }, "add_attributes": { "a" : {"rel":"nofollow"} }, "protocols": { "a":{"href":["ftp","http","https","mailto","relative"]}, "blockquote": {"cite": ["http","https","relative"] }, "q": {"cite": ["http","https","relative"] }, "img": {"src": ["http","https","relative"] } } }

Examples


      {{ '**Foo**' | markdown }} => <p><strong>Foo</strong></p>
    

      {{ '# Foo' | markdown }}  => '<h1>Foo</h1>'
    

      Automatically add rel=nofollow to links
{{ '[Foo link](https://example.com)' | markdown }}  => '<p><a href="https://example.com" rel="nofollow">Foo link</a></p>'
    

      {{ '<b>Foo</b>' | markdown }}  => '<b>Foo</b>'
    

      Tags not enabled by default are removed
{{ '<div class="hello" style="font-color: red; font-size: 99px;">Foo</div>' | markdown }}  => 'Foo'
    

      Attributes not enabled by default are removed
{% assign opts = '{ "elements": [ "div" ] }' %}
{{ '<div class="hello" style="font-color: red; font-size: 99px;">Foo</div>' | markdown: opts }} => <div>Foo</div>
    

      Specify custom tags with attributes
{% assign opts = '{ "elements": [ "div" ], "attributes": { "div": ["class"] } }' %}
{{ '<div class="hello" style="font-color: red; font-size: 99px;">Foo</div>' | markdown: opts }} => <div class="hello">Foo</div>
    

      Using extra_options to override options
{% assign link1 = '[Foo link](https://example.com)' | markdown: nil, '{ "add_attributes": { "a": { "custom_attr": "custom_value", "rel": null } } }' %}
{{ link1 }} => <p><a href="https://example.com" custom_attr="custom_value">Foo link</a></p>

{% assign link2 = '[Foo link](https://example.com)' | markdown: nil, '{ "add_attributes": { "a": {} } }' %}
{{ link2 }} => <p><a href="https://example.com">Foo link</a></p>

{% assign link3 = '[Foo link](https://example.com)' | markdown: nil, '{ "add_attributes": { "a": { "custom_attr": "custom_value" } } }' %}
{{ link3 }} => <p><a href="https://example.com" rel="nofollow" custom_attr="custom_value">Foo link</a></p>

{% assign link4 = '[Foo link](https://example.com)' | markdown %}
{{ link4 }} => <p><a href="https://example.com" rel="nofollow">Foo link</a></p>
    

new_line_to_br (aliases: nl2br)

Replaces every newline in the input with an HTML `<br />` tag.

Params

  • html (untyped) - the text whose newlines should become line breaks; a non-string is stringified first - default: ''

Returns

string - the input with each newline replaced by a `<br />` tag

nl2br

Replaces every newline in the input with an HTML `<br />` tag.

Params

  • html (untyped) - the text whose newlines should become line breaks; a non-string is stringified first - default: ''

Returns

string - the input with each newline replaced by a `<br />` tag

parse_csv_rc

Parses a CSV string into rows

Params

  • input (string) - CSV
  • options (object) - parse csv options - default: {}

Named options

  • convert_to_hash (boolean) - Returns [Array of Objects]

Returns

array - Array

Examples


      {% capture csv %}name,description
name-1,description-1
name-2,description-2
{% endcapture %}
{{ csv | parse_csv }} => [["name","description"],["name-1","description-1"],["name-2","description-2"]]
{{ csv | parse_csv: convert_to_hash: true }} => [{"name":"name-1","description":"description-1"},{"name":"name-2","description":"description-2"}]
    

parse_json (aliases: to_hash)

DEPRECATED: write the JSON as a literal in {% assign %}, which takes one directly and produces the same Hash with no string in between. Note this is a REWRITE and not a rename: the quoted JSON becomes markup, and a value that was interpolated into the string with the `json` filter becomes a plain expression. The rewrite covers JSON written in the TEMPLATE, which is what this filter is mostly used for. A JSON document that arrives at RUNTIME — an `api_call` response body, `download_file` output — reaches Liquid as a string, and `{% assign %}` stores exactly the string it was given; this filter remains the only step that turns one into a Hash. Previously parsed a JSON string into a hash or an array.

Params

  • object (untyped) - JSON to parse — a string; a Hash or an Array is returned unchanged
  • options (object) - set to raw_text true to stop it from unescaping HTML entities - default: {}

Named options

  • raw_text (boolean) - Parses the string as written instead of unescaping HTML entities first (defaults to false)

Returns

untyped - Hash created based on JSON

Examples


      {% assign object = '{ "name": "foo", "bar": {} }' | parse_json %}
{% assign object = { "name": "foo", "bar": {} } %}
Both produce {"name" => "foo", "bar" => {}}
    

      {% assign name = "foo" %}
{% assign object = '{ "name": {{ name | json }} }' | parse_json %}
{% assign object = { "name": name } %}
Both produce {"name" => "foo"}
    

      {% liquid
  assign body = 'https://example.com/data.json' | download_file
  assign object = body | parse_json
%}
{{ object.name }} => 'foo'
    

      {% liquid
  assign text = '{ "name": "foo", "bar": {} }'
  assign object = text | parse_json
%}
{{ object.name }} => 'foo'
    

      {% liquid
  assign text = '{ "key": "abc &amp; def" }'
  assign object = text | parse_json
%}
{{ object.key }} => abc & def
    

      {% comment %}raw_text: true keeps HTML entities as written instead of unescaping them
before the JSON is parsed.{% endcomment %}
{% liquid
  assign text = '{ "key": "abc &amp; def" }'
  assign object = text | parse_json: raw_text: true
%}
{{ object.key }} => abc &amp; def
    

prepend_to_array

Inserts an element at the beginning of the array

Params

  • array (array) - array to which you prepend a new element
  • item (untyped) - item you prepend to the array

Returns

array - array to which you prepend the item given as the second parameter

Examples


      {% assign array = 'a,b,c' | split: ',' %}
{{ array | array_prepend: 'd' }} => ['d', 'a', 'b', 'c']
    

reject

Returns every element that does not match all the given field conditions

Params

  • objects (array) - array of objects to be processed
  • conditions (object) - hash with conditions { field_name: value } - default: {}

Keys other than these are accepted too.

Returns

array - with objects from collection that don't match provided conditions

Examples


      {{ objects }} => [{"foo":1,"bar":"a"},{"foo":2,"bar":"b"},{"foo":3,"bar":"c"},{"foo":2,"bar":"d"}]
{{ objects | array_reject: foo: 2 }} => [{"foo":1,"bar":"a"},{"foo":3,"bar":"c"}]
    

remove_hash_key

Removes the given key from the hash and returns the value it held

Params

  • hash (object) - hash to remove the key from
  • key (string) - key to remove

Returns

untyped - value which was assigned to a deleted key. If the key did not exist in the first place, null is returned.

Examples


      {% liquid
  assign hash = '{ "a": "1", "b": "2"}' | parse_json
  assign a_value = hash | hash_delete_key: "a"
%}
{{ a_value }} => "1"
{{ hash }} => { "b": "2" }
    

rotate

Rotates the array left by the given number of positions

Params

  • array (array) - array to be rotated
  • count (number) - number of times to rotate the input array; must be a whole number, optional, defaults to 1 - default: 1

Returns

array - the input array rotated by a number of times given as the second parameter; [1,2,3,4] rotated by 2 gives [3,4,1,2]

Examples


      {% assign numbers = "1,2,3" | split: "," %}
{{ numbers | array_rotate }} => [2,3,1]
    

select

Returns every element matching all the given field conditions

Params

  • objects (array) - array of objects to be processed
  • conditions (object) - hash with conditions { field_name: value } - default: {}

Keys other than these are accepted too.

Returns

array - with objects from collection that matches provided conditions

Examples


      {{ objects }} => [{"foo":1,"bar":"a"},{"foo":2,"bar":"b"},{"foo":3,"bar":"c"},{"foo":2,"bar":"d"}]
{{ objects | array_select: foo: 2 }} => [{"foo":2,"bar":"b"},{"foo":2,"bar":"d"}]
    

sha1

Returns the SHA1 digest of the string

Params

  • object (string) - input object that you want to obtain the digest for

Returns

string - SHA1 digest of the input object

Examples


      {{ 'foo' | sha1 }} => '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33'
    

shuffle_array

Returns the array with its elements in random order

Params

  • array (array) - array of objects to be processed

Returns

array - array with shuffled items

Examples


      {{ items }} => [1, 2, 3, 4]
{{ items | array_shuffle }} => [3, 2, 4, 1]
    

sort_by

Sorts an array of objects by the value of the given property

Params

  • input (array) - Array of Hash to be sorted by a key
  • property (untyped) - property by which to sort an Array of Hashes

Returns

array - Sorted object (Array of Hash)

Examples


      array1 is [{"title": "Tester", "value": 1}, {"title": "And", "value": 2}]
{{ array1 | array_sort_by: "title" }}
    

subtract_array

Returns the elements of the first array that are not in the second

Params

  • array (array) - array of objects to be processed
  • other_array (array) - array of objects to be processed

Returns

array - that is a difference between two arrays

Examples


      {% liquid
  assign array = '1,2' | split: ','
  assign other_array = '2' | split: ','
%}

{{ array | array_subtract: other_array }} => [1]
    

sum_array

Sums all the numbers in the array

Params

  • array (array) - array with values to be summarised

Returns

number - summarised value of array

Examples


      {% assign numbers = '[1,2,3]' | parse_json %}
{{ numbers | array_sum }} => 6
    

to_hash

DEPRECATED: write the JSON as a literal in {% assign %}, which takes one directly and produces the same Hash with no string in between. Note this is a REWRITE and not a rename: the quoted JSON becomes markup, and a value that was interpolated into the string with the `json` filter becomes a plain expression. The rewrite covers JSON written in the TEMPLATE, which is what this filter is mostly used for. A JSON document that arrives at RUNTIME — an `api_call` response body, `download_file` output — reaches Liquid as a string, and `{% assign %}` stores exactly the string it was given; this filter remains the only step that turns one into a Hash. Previously parsed a JSON string into a hash or an array.

Params

  • object (untyped) - JSON to parse — a string; a Hash or an Array is returned unchanged
  • options (object) - set to raw_text true to stop it from unescaping HTML entities - default: {}

Named options

  • raw_text (boolean) - Parses the string as written instead of unescaping HTML entities first (defaults to false)

Returns

untyped - Hash created based on JSON

Examples


      {% assign object = '{ "name": "foo", "bar": {} }' | parse_json %}
{% assign object = { "name": "foo", "bar": {} } %}
Both produce {"name" => "foo", "bar" => {}}
    

      {% assign name = "foo" %}
{% assign object = '{ "name": {{ name | json }} }' | parse_json %}
{% assign object = { "name": name } %}
Both produce {"name" => "foo"}
    

      {% liquid
  assign body = 'https://example.com/data.json' | download_file
  assign object = body | parse_json
%}
{{ object.name }} => 'foo'
    

      {% liquid
  assign text = '{ "name": "foo", "bar": {} }'
  assign object = text | parse_json
%}
{{ object.name }} => 'foo'
    

      {% liquid
  assign text = '{ "key": "abc &amp; def" }'
  assign object = text | parse_json
%}
{{ object.key }} => abc & def
    

      {% comment %}raw_text: true keeps HTML entities as written instead of unescaping them
before the JSON is parsed.{% endcomment %}
{% liquid
  assign text = '{ "key": "abc &amp; def" }'
  assign object = text | parse_json: raw_text: true
%}
{{ object.key }} => abc &amp; def
    

to_json

Serializes the value as JSON

Params

  • object (untyped) - object you want a JSON representation of

Returns

string - JSON formatted string containing a representation of object.

Examples


      {{ user | json }} => {"name":"Mike","email":"[email protected]"}
    

to_xml_rc

Serializes a hash as XML

Params

  • object (objectarray) - hash object that will be represented as xml; an array is written as a series of `<anon>` elements
  • options (object) - attr_prefix: use '@' for element attributes - default: {}

Named options

  • attr_prefix (boolean) - Writes keys beginning with '@' as element attributes rather than as child elements (defaults to false)

Returns

string - String containing XML

Examples


      {% liquid
  assign object = '{"letter":[{"title":[{"maxlength":"10","content":" Quote Letter "}]}]}' | parse_json
  assign xml = object | to_xml
%}
{{ object }} => '<letter> <title maxlength="10"> Quote Letter </title> </letter>'
    

translate

Looks up a translation by key

Params

  • key (string) - translation key
  • options (object) - values passed to translation string - default: {}

Named options

  • locale (string) - Enforces using specified locale instead of value provided via `?language=<locale>`
  • default (string) - Specifies the default for a scenario when translation is missing. If fallback not set to true, system will automatically try to load english translation first
  • fallback (boolean) - specify whether the system should try to fallback to english if translation is missing for the current locale
  • scope (string) - Looks the key up under this prefix, so `t: scope: 'drinks.alcoholic'` resolves `beer` as `drinks.alcoholic.beer`
  • count (number) - Selects the plural form of the translation, and is interpolated as `%{count}`

Keys other than these are accepted too.

Returns

untyped - Translation value taken from translations YML file for the key given as parameter. The value is assumed to be html safe, please use `t_escape` if you provide unsafe argument which can potentially include malicious script.

Examples


      {{ 'beer' | t }} => 'cerveza'
    

      {{ 'drinks.alcoholic.beer' | t }} => 'piwo'
    

      {{ 'non_existing_translation' | t: default: 'Missing', fallback: false }} => 'Missing'
    

      {{ 'user-greeting' | t: username: 'Mike' }} => 'Hello Mike!'
    

translate_escape

Escapes unsafe arguments passed to the translation and then returns its value

Params

  • key (string) - translation key
  • options (object) - values passed to translation string - default: {}

Named options

  • locale (string) - Enforces using specified locale instead of value provided via `?language=<locale>`
  • default (string) - Specifies the default for a scenario when translation is missing
  • fallback (boolean) - specify whether the system should try to fallback to english if translation is missing
  • scope (string) - Looks the key up under this prefix
  • count (number) - Selects the plural form of the translation, and is interpolated as `%{count}`

Keys other than these are accepted too.

Returns

untyped - translation value taken from translations YML file for the key given as parameter

Examples


      en.yml
en:
  user-greeting: Hello %{username}

{{ 'user-greeting' | t_escape: username: '<script>alert("hello")</script>Mike' }}
=> will not evaluate the script, it will print out:
Hello <script>alert("hello")</script>Mike
    

www_form_encode_rc

Encodes the object as application/x-www-form-urlencoded data

Params

  • object (objectarray) - data object

Returns

string - This generates application/x-www-form-urlencoded data defined in HTML5 from given object.

Examples


      assign object = '{"foo": "bar", "zoo": [{ "xoo": 1 }, {"xoo": 2}]}' | parse_json
assign form_data = object | www_form_encode
  => "foo=bar&zoo[0][xoo]=555&zoo[1][xoo]=999",
    

xml_to_hash

Parses an XML string into a hash

Params

  • xml (string) - String containing valid XML
  • options (object) - attr_prefix: use '@' for element attributes, force_array: always try to use arrays for child elements - default: {}

Named options

  • attr_prefix (boolean) - Reads an element's attributes under keys prefixed with '@', telling them apart from child elements of the same name (defaults to false)
  • force_array (boolean) - Wraps every child element in an array, whether or not it repeats (defaults to true)

Returns

object - Hash created based on XML

Examples


      {% liquid
  assign text = '<?xml version="1.0" encoding="UTF-8"?><letter><title maxlength="10"> Quote Letter </title></letter>'
  assign object = text | parse_xml
%}
{{ object }} => '{"letter":[{"title":[{"maxlength":"10","content":" Quote Letter "}]}]}'
    

abs

Returns the absolute value of a number

Params

  • input (untyped) - number to process, or a string holding one — Liquid coerces it

Returns

number - the absolute value

Examples


      {{ -3 | abs }}
    

append

Adds a given string to the end of a string

Params

  • input (untyped) - value to process; any value is stringified first
  • string (untyped) - text to append

Returns

string - the input with the string appended

Examples


      {%-  assign path = product.url -%}

{{ request.origin | append: path }}
    

at_least

Limits a number to a minimum value

Params

  • input (untyped) - number to process, or a string holding one — Liquid coerces it
  • n (untyped) - the minimum to return

Returns

number - the input, or the minimum when the input is smaller

Examples


      {{ 4 | at_least: 5 }}
{{ 4 | at_least: 3 }}
    

at_most

Limits a number to a maximum value

Params

  • input (untyped) - number to process, or a string holding one — Liquid coerces it
  • n (untyped) - the maximum to return

Returns

number - the input, or the maximum when the input is larger

Examples


      {{ 6 | at_most: 5 }}
{{ 4 | at_most: 5 }}
    

base64_url_safe_decode

Decodes a string in URL-safe [Base64 format](https://developer.mozilla.org/en-US/docs/Glossary/Base64)

Params

  • input (untyped) - string to process

Returns

string - the decoded string

Examples


      {{ 'YSBiL2M_' | base64_url_safe_decode }}
    

base64_url_safe_encode

Encodes a string to URL-safe [Base64 format](https://developer.mozilla.org/en-US/docs/Glossary/Base64)

Params

  • input (untyped) - string to process

Returns

string - the URL-safe Base64 representation of the input

Examples


      {{ 'a b/c?' | base64_url_safe_encode }}
    

capitalize

Capitalizes the first word in a string and downcases the remaining characters

Params

  • input (untyped) - string to process

Returns

string - the input with its first character capitalized

Examples


      {{ 'this sentence should start with a capitalized word.' | capitalize }}
    

ceil

Rounds a number up to the nearest integer

Params

  • input (untyped) - number to process, or a string holding one — Liquid coerces it

Returns

number - the input rounded up to the nearest integer

Examples


      {{ 1.2 | ceil }}
    

concat

Joins two arrays into one; duplicates are kept, so pipe through uniq to remove them

Params

  • input (untyped) - array to process
  • array (untyped) - array to append to the input

Returns

array - the two arrays joined into one

Examples


      {%- assign types_and_vendors = collection.all_types | concat: collection.all_vendors -%}

Types and vendors:

{% for item in types_and_vendors -%}
  {%- if item != blank -%}
    - {{ item }}
  {%- endif -%}
{%- endfor %}
    

date

Converts a timestamp into another date format. The `date` filter accepts the same parameters as Ruby's strftime method for formatting the date. For a list of shorthand formats, refer to the [Ruby documentation](https://ruby-doc.org/core-3.1.1/Time.html#method-i-strftime) or [strftime reference and sandbox](http://www.strfti.me/).

Params

  • input (untyped) - time to format — a string, a time, a date, or seconds since the epoch
  • format (untyped) - the desired date format

Returns

string - the formatted date

Examples


      {{ article.created_at | date: '%B %d, %Y' }}
    

      {{ 'now' | date: '%B %d, %Y' }}
    

      {{ article.created_at | date: format: 'abbreviated_date' }}
    

      {{ article.created_at | date: format: 'month_day_year' }}
    

default

Returns a fallback value when the input is nil, false or empty

Params

  • input (untyped) - value to use unless it is nil, false or empty
  • default_value (untyped) - value to fall back on when the input is nil, false or empty - default: ''
  • options (untyped) - set allow_false: true to treat false as a value rather than as empty - default: {}

Returns

untyped - the input, or the default value when the input is nil, false or empty

Examples


      {{ product.selected_variant.url | default: product.url }}
    

      {%- assign display_price = false -%}

{{ display_price | default: true, allow_false: true }}
    

divided_by

Divides a number by a given number. The `divided_by` filter produces a result of the same type as the divisor. This means if you divide by an integer, the result will be an integer, and if you divide by a float, the result will be a float

Params

  • input (untyped) - number to process, or a string holding one — Liquid coerces it
  • operand (untyped) - number to divide by; an integer operand keeps the result an integer

Returns

number - the quotient

Examples


      {{ 4 | divided_by: 2 }}

# divisor is an integer
{{ 20 | divided_by: 7 }}

# divisor is a float
{{ 20 | divided_by: 7.0 }}
    

downcase

Converts a string to all lowercase characters

Params

  • input (untyped) - string to process

Returns

string - the input in lowercase

Examples


      {{ product.title | downcase }}
    

escape

Escapes special characters in HTML, such as `<>`, `'`, and `&`, and converts characters into escape sequences. The filter doesn't effect characters within the string that don’t have a corresponding escape sequence."

Params

  • input (untyped) - string to process

Returns

string - the input with HTML special characters escaped

Examples


      {{ '&lt;p&gt;Text to be escaped.&lt;/p&gt;' | escape }}
    

escape_once

Escapes a string without changing characters that have already been escaped

Params

  • input (untyped) - string to process

Returns

string - the input escaped, leaving entities that are already escaped untouched

Examples


      {{ '&lt;p&gt;Hello &amp; welcome&lt;/p&gt;' | escape_once }}
    

find

Returns the first item in an array with a specific property value. This requires you to provide both the property name and the associated value.

Params

  • input (untyped) - the array to search
  • property (untyped) - the property name to test on each item
  • target_value (untyped) - the value the property must equal. Omitted, any truthy value matches - default: nil

Returns

untyped - the first matching item, or nil when nothing matches

Examples


      {{ products | find: 'type', 'shirt' }}
    

find_index

Returns the index of the first item in an array with a specific property value. This requires you to provide both the property name and the associated value.

Params

  • input (untyped) - the array to search
  • property (untyped) - the property name to test on each item
  • target_value (untyped) - the value the property must equal. Omitted, any truthy value matches - default: nil

Returns

number - the index of the first matching item, or nil when nothing matches

Examples


      {{ products | find_index: 'type', 'shirt' }}
    

first

Returns the first item in an array

Params

  • array (untyped) - array to process

Returns

untyped - the first item of the array

Examples


      {%- assign first_product = collection.products | first -%}

{{ first_product.title }}
    

      {{ collection.products.first.title }}
    

floor

Rounds a number down to the nearest integer

Params

  • input (untyped) - number to process, or a string holding one — Liquid coerces it

Returns

number - the input rounded down to the nearest integer

Examples


      {{ 1.2 | floor }}
    

h

Escapes a string, so it can be safely rendered as HTML. An alias of `escape`

Params

  • input (untyped) - string to process

Returns

string - the input with HTML special characters escaped

Examples


      {{ '&lt;script&gt;' | h }}
    

has

Tests if any item in an array has a specific property value. This requires you to provide both the property name and the associated value.

Params

  • input (untyped) - the array to search
  • property (untyped) - the property name to test on each item
  • target_value (untyped) - the value the property must equal. Omitted, any truthy value matches - default: nil

Returns

boolean - whether any item matches

Examples


      {% if products | has: 'type', 'shirt' %}
    

join

Combines all of the items in an array into a single string, separated by a space

Params

  • input (untyped) - array to process
  • glue (untyped) - string inserted between the items; defaults to a single space - default: ' '

Returns

string - the items joined into one string

Examples


      {{ collection.all_tags | join }}
    

      {{ collection.all_tags | join: ', ' }}
    

last

Returns the last item in an array

Params

  • array (untyped) - array to process

Returns

untyped - the last item of the array

Examples


      {%- assign last_product = collection.products | last -%}

{{ last_product.title }}
    

      {{ collection.products.last.title }}
    

lstrip

Strips all whitespace from the left of a string

Params

  • input (untyped) - string to process

Returns

string - the input without leading whitespace

Examples


      {%- assign text = '  Some potions create whitespace.      ' -%}

"{{ text }}"
"{{ text | lstrip }}"
    

minus

Subtracts a given number from another number

Params

  • input (untyped) - number to process, or a string holding one — Liquid coerces it
  • operand (untyped) - number to subtract

Returns

number - the difference

Examples


      {{ 4 | minus: 2 }}
    

modulo

Returns the remainder of dividing a number by a given number

Params

  • input (untyped) - number to process, or a string holding one — Liquid coerces it
  • operand (untyped) - number to divide by, returning the remainder

Returns

number - the remainder

Examples


      {{ 12 | modulo: 5 }}
    

newline_to_br

Converts newlines (`\n`) in a string to HTML line breaks (`<br>`)

Params

  • input (untyped) - string to process

Returns

string - the input with each newline replaced by a line-break tag

Examples


      {{ product.description | newline_to_br }}
    

plus

Adds two numbers

Params

  • input (untyped) - number to process, or a string holding one — Liquid coerces it
  • operand (untyped) - number to add

Returns

number - the sum

Examples


      {{ 2 | plus: 2 }}
    

prepend

Adds a given string to the beginning of a string

Params

  • input (untyped) - value to process; any value is stringified first
  • string (untyped) - text to put in front of the input

Returns

string - the input with the string in front of it

Examples


      {%- assign origin = request.origin -%}

{{ product.url | prepend: origin }}
    

remove

Removes any instance of a substring inside a string

Params

  • input (untyped) - string to process
  • string (untyped) - substring to remove everywhere it occurs

Returns

string - the input without any occurrence of the substring

Examples


      {{ "I can't do it!" | remove: "'t" }}
    

remove_first

Removes the first instance of a substring inside a string

Params

  • input (untyped) - string to process
  • string (untyped) - substring to remove from its first occurrence only

Returns

string - the input without the first occurrence of the substring

Examples


      {{ "I hate it when I accidentally spill my duplication potion accidentally!" | remove_first: ' accidentally' }}
    

remove_last

Removes the last instance of a substring inside a string

Params

  • input (untyped) - string to process
  • string (untyped) - the substring to look for

Returns

string - the input without the last occurrence of the substring

Examples


      {{ 'a-b-c-' | remove_last: '-' }}
    

replace

Replaces any instance of a substring inside a string with a given string

Params

  • input (untyped) - string to process
  • string (untyped) - substring to look for
  • replacement (untyped) - text to put in its place - default: ''

Returns

string - the input with every occurrence replaced

Examples


      {{ product.handle | replace: '-', ' ' }}
    

replace_first

Replaces the first instance of a substring inside a string with a given string

Params

  • input (untyped) - string to process
  • string (untyped) - substring to look for
  • replacement (untyped) - text to put in place of the first occurrence - default: ''

Returns

string - the input with the first occurrence replaced

Examples


      {{ product.handle | replace_first: '-', ' ' }}
    

replace_last

Replaces the last instance of a substring inside a string with a given string

Params

  • input (untyped) - string to process
  • string (untyped) - the substring to look for
  • replacement (untyped) - the string to substitute in

Returns

string - the input with the last occurrence replaced

Examples


      {{ 'red, red, red' | replace_last: 'red', 'blue' }}
    

reverse

Reverses the order of the items in an array

Params

  • input (untyped) - array to process

Returns

array - the items in reverse order

Examples


      Original order:
{{ collection.products | map: 'title' | join: ', ' }}

Reverse order:
{{ collection.products | reverse | map: 'title' | join: ', ' }}
    

      {{ collection.title | split: '' | reverse | join: '' }}
    

round

Rounds a number to the nearest integer

Params

  • input (untyped) - number to process, or a string holding one — Liquid coerces it
  • n (untyped) - number of decimal places to keep; defaults to 0 - default: 0

Returns

number - the rounded number

Examples


      {{ 2.7 | round }}
{{ 1.3 | round }}
    

      {{ 3.14159 | round: 2 }}
    

rstrip

Strips all whitespace from the right of a string

Params

  • input (untyped) - string to process

Returns

string - the input without trailing whitespace

Examples


      {%- assign text = '  Some potions create whitespace.      ' -%}

"{{ text }}"
"{{ text | rstrip }}"
    

size

Returns the size of a string or array. The size of a string is the number of characters that the string includes. The size of an array is the number of items in the array.

Params

  • input (untyped) - value to measure

Returns

number - the number of characters, items or pairs

Examples


      {{ collection.title | size }}
{{ collection.products | size }}
    

      {% if collection.products.size &gt;= 10 %}
  There are 10 or more products in this collection.
{% else %}
  There are less than 10 products in this collection.
{% endif %}
    

slice

Returns a substring or series of array items, starting at a given 0-based index. By default, the substring has a length of one character, and the array series has one array item. However, you can provide a second parameter to specify the number of characters or array items.

Params

  • input (untyped) - string or array to take from
  • offset (untyped) - zero-based position to start at; a negative value counts back from the end
  • length (untyped) - how many characters or items to take; defaults to 1 - default: nil

Returns

untyped - the selected part of the input

Examples


      {{ collection.title | slice: 0 }}
{{ collection.title | slice: 0, 5 }}

{{ collection.all_tags | slice: 1, 2 | join: ', ' }}
    

      {{ collection.title | slice: -3, 3 }}
    

sort

Sorts the items in an array in case-sensitive alphabetical, or numerical, order

Params

  • input (untyped) - array to process
  • property (untyped) - property to sort each item by; sorts the items themselves when omitted - default: nil

Returns

array - the items sorted, case-sensitively

Examples


      {% assign tags = collection.all_tags | sort %}

{% for tag in tags -%}
  {{ tag }}
{%- endfor %}
    

      {% assign products = collection.products | sort: 'price' %}

{% for product in products -%}
  {{ product.title }}
{%- endfor %}
    

sort_natural

Sorts the items of an array, ignoring case. Not for numbers: values are compared as strings, so 10 sorts before 9

Params

  • input (untyped) - array to process
  • property (untyped) - property to sort each item by, case-insensitively; sorts the items themselves when omitted - default: nil

Returns

array - the items sorted, ignoring case

Examples


      {% assign tags = collection.all_tags | sort_natural %}

{% for tag in tags -%}
  {{ tag }}
{%- endfor %}
    

      {% assign products = collection.products | sort_natural: 'title' %}

{% for product in products -%}
  {{ product.title }}
{%- endfor %}
    

strip

Strips all whitespace from the left and right of a string

Params

  • input (untyped) - string to process

Returns

string - the input without leading or trailing whitespace

Examples


      {%- assign text = '  Some potions create whitespace.      ' -%}

"{{ text }}"
"{{ text | strip }}"
    

strip_html

Strips all HTML tags from a string

Params

  • input (untyped) - string to process

Returns

string - the input with every HTML tag removed

Examples


      &lt;!-- With HTML --&gt;
{{ product.description }}

&lt;!-- HTML stripped --&gt;
{{ product.description | strip_html }}
    

strip_newlines

Strips all newline characters (line breaks) from a string

Params

  • input (untyped) - string to process

Returns

string - the input with every newline removed

Examples


      &lt;!-- With newlines --&gt;
{{ product.description }}

&lt;!-- Newlines stripped --&gt;
{{ product.description | strip_newlines }}
    

sum

Returns the sum of all elements in an array

Params

  • input (untyped) - the array to search
  • property (untyped) - sum this property of each item instead of the item itself - default: nil

Returns

number - the total

Examples


      {{ items | sum: 'quantity' }}
    

times

Multiplies a number by a given number

Params

  • input (untyped) - number to process, or a string holding one — Liquid coerces it
  • operand (untyped) - number to multiply by

Returns

number - the product

Examples


      {{ 2 | times: 2 }}
    

truncate

Truncates a string down to a given number of characters. If the specified number of characters is less than the length of the string, then an ellipsis (`...`) is appended to the truncated string. The ellipsis is included in the character count of the truncated string.

Params

  • input (untyped) - string to process
  • length (untyped) - maximum length of the result, counting the ellipsis; defaults to 50 - default: 50
  • truncate_string (untyped) - string appended when the input is shortened; defaults to '...' - default: "..."

Returns

string - the shortened string

Examples


      {{ article.title | truncate: 15 }}
    

      {{ article.title | truncate: 15, '--' }}
{{ article.title | truncate: 15, '' }}
    

truncatewords

Truncates a string down to a given number of words. If the specified number of words is less than the number of words in the string, then an ellipsis (`...`) is appended to the truncated string. HTML tags are treated as words, so you should strip any HTML from truncated content. If you don't strip HTML, then > closing HTML tags can be removed, which can result in unexpected behavior.

Params

  • input (untyped) - string to process
  • words (untyped) - how many words to keep; defaults to 15 - default: 15
  • truncate_string (untyped) - string appended when the input is shortened; defaults to '...' - default: "..."

Returns

string - the input cut to the given number of words

Examples


      {{ article.content | strip_html | truncatewords: 15 }}
    

      {{ article.content | strip_html | truncatewords: 15, '--' }}

{{ article.content | strip_html | truncatewords: 15, '' }}
    

uniq

Removes any duplicate items in an array

Params

  • input (untyped) - array to process
  • property (untyped) - property to compare items by; compares the items themselves when omitted - default: nil

Returns

array - the items without duplicates

Examples


      {% assign potion_array = 'invisibility, health, love, health, invisibility' | split: ', ' %}

{{ potion_array | uniq | join: ', ' }}
    

upcase

Converts a string to all uppercase characters

Params

  • input (untyped) - string to process

Returns

string - the input in uppercase

Examples


      {{ product.title | upcase }}
    

url_decode

Decodes any [percent-encoded](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding) characters in a string

Params

  • input (untyped) - string to process

Returns

string - the decoded string

Examples


      {{ 'test%40test.com' | url_decode }}
    

url_encode

Percent-encodes a string so it can be used in a URL, converting spaces to a + character

Params

  • input (untyped) - string to process

Returns

string - the URL-encoded string

Examples


      {{ '[email protected]' | url_encode }}
    

where

Filters an array to include only items with a specific property value. This requires you to provide both the property name and the associated value.

Params

  • input (untyped) - the array to search
  • property (untyped) - the property name to test on each item
  • target_value (untyped) - the value the property must equal. Omitted, any truthy value matches - default: nil

Returns

array - the matching items

Examples


      {{ products | where: 'type', 'shirt' }}
    

Questions?

We are always happy to help with any questions you may have.

contact us