Types
In Twig, data is categorised into different types, much like in many programming languages. Understanding these types is essential for effective template development, as it influences how data is processed and displayed in your ShopWired store.
Common data types in Twig
String
A string is a sequence of characters, typically used for textual data. In Twig, strings can be enclosed in single or double quotes. For example:
{{ "Hello, world!" }}
{{ 'ShopWired' }}
Number
Numbers in Twig can be or . These are used for mathematical operations or any data that requires numeric representation. For example:
{{ 42 }}
{{ 3.14 }}
Boolean
A boolean represents a and can be either true
or false
. For example:
{{ true }}
{{ false }}
Array
An array is a collection of values, which can be of different types. Arrays are useful for storing multiple values in a single variable. For example:
{% set products = ['Nike Trainers', 'Adidas Trainers', 'Versace Trainers'] %}
{{ products[0] }} {# Outputs 'Nike Trainers' #}
Object
In Twig, objects are often used to access properties or methods. They are typically used when working with data structures like products or visitors. They can also be used for custom objects. For example:
{{ product.name }}
{{ customer.first_name }}
Null
The null type represents a variable with no value. It’s useful for checking whether a variable has been set or is empty. For example:
{% set custom_variable = null %}
{{ custom_variable is null }} {# Outputs 'true' #}
Date and Time
Twig provides special keywords and functions to handle date and time. One of the most commonly used is the 'now'
keyword, which represents the current date and time. This can be especially useful for displaying the current date, calculating time differences, or formatting dates.
<p>Current date and time: {{ "now" | date("Y-m-d H:i:s") }}</p>
This will output the current date and time, formatted as YYYY-MM-DD HH:MM:SS
.