Assigning a variable
Variables are placeholders for values that change.
Variables output values in your snippets. Variable names are denoted by double curly braces: {{
and }}
. To render the content of a variable called title
with the value hello world
:
<p>{{ title }}</p>
<p>hello world</p>
Initializing variables
You can initialize variables with the assign
or capture
tags.
assign
Creates a new variable.
{% assign foo = "bar" %}
capture
Captures the string inside of the opening and closing tags and assigns it to a variable. Variables created through capture
are strings.
{% capture foo %}I am being captured.{% endcapture %}
Types
There are five variable types: string, number, boolean, nil
, and array.
String
Declare a string by wrapping a variable’s value in single ('
) or double quotes ("
):
{% assign my_string = "Hello World!" %}
Number
Numbers include floats and integers:
{% assign my_int = 25 %}
{% assign my_float = 3.14159 %}
Boolean
Booleans are either true
or false
. No quotations are necessary when declaring a boolean:
{% assign foo = true %}
{% assign bar = false %}
nil
nil
is a special empty value that is returned when we have no results. It is not a string with the characters “nil”.
nil
is treated as false
in the conditions of if
blocks and other tags that check the truthfulness of a statement.
Tags or outputs that return nil
will not print anything to the page.
<p>The current user is {{ foo }}</p>
<p>The current user is </p>
Arrays
Arrays hold lists of variables of any type. You can use square bracket [ ]
notation to access a specific item in an array, and array indexing starts at zero.
<!-- if users = "Tobi", "Laura", "Tetsuro", "Adam" -->
{{ users[0] }}
{{ users[1] }}
{{ users[3] }}
Tobi
Laura
Adam
You cannot initialize arrays. You can, however, use the split
filter to break a string into an array of substrings.
Truthy and falsey
Anything that returns true
in a conditional is called truthy. Anything that returns false
in a conditional is called falsy. All variables can be described as either truthy or falsy.
All values are truthy except nil
and false
, even empty strings, arrays, and zero.
truthy | falsy | |
---|---|---|
true |
✓ | |
false |
✓ | |
nil |
✓ | |
string (e.g., "foo" ) |
✓ | |
empty string (i.e., "" ) |
✓ | |
zero (i.e., 0 ) |
✓ | |
non-zero integer (e.g., 10 or -10 ) |
✓ | |
non-zero float (e.g., 3.14 ) |
✓ | |
array (e.g., ["foo", "bar", "baz"] ) |
✓ | |
empty array (e.g., [] ) |
✓ |
Find a typo? Something is wrong in this documentation? Fork and edit it!