Variables, objects and attributes
In Twig, variables, objects, and attributes are essential elements that allow you to access and manipulate data within your templates. Understanding how to work with these elements is crucial for creating dynamic and flexible templates within your ShopWired theme.
Variables
Variables in Twig are placeholders for data. They can hold strings, numbers, arrays, or objects and are typically defined using the set tag or passed into the template from your ShopWired store's backend.
Example of setting and using variables
{% set productName = "T-shirt" %}
<p>The product is: {{ productName }}</p>
In this example, the variable productName is set to "T-shirt", and it's used within the template to display the product name.
Objects
Objects in Twig represent more complex data structures, like products, visitors, or orders. Objects can have multiple attributes, which you can access to retrieve specific information.
Example of accessing object properties
To access an object's properties (attributes), you use dot notation:
<p>Product name: {{ product.title }}</p>
<p>Product price: {{ product.price }}</p>
Here, product.title and product.price access the title and price properties of the product object.
Arrays and objects
In Twig, arrays and objects are accessed similarly. You can use dot notation to access object properties or use bracket notation for arrays.
Example with arrays:
{% set items = ['Nike Trainers', 'Adidas Trainers', 'Versace Trainers'] %}
<p>First item: {{ items[0] }}</p>
Example with objects:
<p>First attribute: {{ product.attributes[0].value }}</p>