Objects
Objects, also known as hashes, are a powerful way to store and organize related data. An object is essentially a collection of key-value pairs. Think of it like a file folder where each document has a specific label (the key) and content (the value).
Instead of dynamically assigning many separate variables using captures, in Liquid you can create a set of key-value pairs within a single variable (the object).
Syntax
Define an object using the assign
tag combined with the default
filter that contains the key-value pairs:
{% assign object_name = null | default: key1: "value1", key2: "value2" %}
A value among the key-value pairs can be a string, numeric, or another variable. That variable can also contain an object. This way it is possible to create nested objects. This can be used instead of capturing dynamic variables with more than one variable element.
Accessing Data from an Object
To access a value within an object, you use dot notation (.
).
value1: {{ object_name.key1 }}
value2: {{ object.name.key2 }}
Example
Let's create an object to hold information about a client. We'll include their name, industry, and a nested object for their address.
First, we define the address
object:
{% comment %} Define the nested address object first {% endcomment %}
{% assign client_address = client_address | default: street: "Innovation Drive 22", city: "Capital City", zip_code: "B-1000" %}
Next, we define the main client
object and assign the client_address
object as one of its values:
{% comment %} Define the main client object {% endcomment %}
{% assign client = client | default: name: "Future Solutions Ltd.", industry: "Consulting", address: client_address %}
Input:
Client Name: {{ client.name }}
Industry: {{ client.industry }}
Street: {{ client.address.street }}
City: {{ client.address.city }}
Output:
Client Name: Future Solutions Ltd.
Industry: Consulting
Street: Innovation Drive 22
City: Capital City
Using objects is an excellent practice for grouping complex data. It keeps your templates organized and makes your data structures intuitive and scalable.
Updated 10 days ago