Difference between revisions of "Liquid Basics"

From Spiffy Stores Knowledge Base

 
(31 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 +
Spiffy Stores gives you 100% control over the HTML and CSS for your online storefront. Our themes use standard HTML and CSS, with dynamic tags from a templating language called "Liquid" to display dynamic data. This helps you transform your design into a dynamic e-commerce web site as quickly as possible.
 +
 
This is an introduction to the Spiffy Stores Liquid template syntax, and a reference for Spiffy Stores-specific Tags and Filters.
 
This is an introduction to the Spiffy Stores Liquid template syntax, and a reference for Spiffy Stores-specific Tags and Filters.
  
 
Liquid is the templating engine for customizing your store layout. It's a small and fast template language which is quick and easy to learn but contains very powerful features for full customization.
 
Liquid is the templating engine for customizing your store layout. It's a small and fast template language which is quick and easy to learn but contains very powerful features for full customization.
  
The Spiffy Stores Liquid Variables Reference can be found [[Liquid Variable Reference|here]].
+
You can use a template language such as Liquid to substitute variable data into a page layout. For example, each product page is defined by the <code>product.liquid</code> template. This file contains the HTML that describes the layout of the various elements on a product page. Within this template, you will find various Liquid tags and variables that help to display different data for each product.
 +
 
 +
For example, a product template will usually contain a product title, using the <code><nowiki>{{ product.title }}</nowiki></code> Liquid variable. A different title will be used for each different product that is displayed, as the Liquid variable is substituted for the actual product title.
  
 
== Basics ==
 
== Basics ==
  
There are two types of markup in liquid: Output and Tag.
+
There are two types of markup in liquid: '''Output''' and '''Tag'''.
  
* Output is surrounded by <pre> {{ two curly brackets }} </pre>
+
* '''Output''' is surrounded by - <code><nowiki>{{ two curly brackets }}</nowiki></code>
* Tags are surrounded by <pre> {% a curly bracket and a percent %} </pre>
+
* '''Tags''' are surrounded by - <code><nowiki>{% a curly bracket and a percent %}</nowiki></code>
  
 
Output blocks will always be replaced with the data which they reference.
 
Output blocks will always be replaced with the data which they reference.
  
For instance if your liquid template has a product object exposed to it you can print the name of the product to the screen by referencing <pre> {{ product.title }} </pre>
+
For instance if your liquid template has a product object exposed to it you can print the name of the product to the screen by referencing <code><nowiki>{{ product.title }}</nowiki></code>
  
Tags drive the logic of templates. They are responsible for loops and branching logic such as If / Else.
+
Tags allow you to control the logic of templates. They are responsible for loops and branching logic such as <code>If / Else</code>.
  
 
== Output ==
 
== Output ==
  
Here is a simple example of Output:
+
Here is a simple example of '''Output'''. The Liquid code contains variables that will be replaced by the actual values when the template is rendered.
  
 
<pre>
 
<pre>
Hello {{name}}
+
Hello {{ name }}
Hello {{user.name}}
+
Hello {{ user.name }}
 
Hello {{ 'fred' }}
 
Hello {{ 'fred' }}
 
</pre>
 
</pre>
  
=== Acceptable Tags and Comments ===
+
For a full description of all the Liquid variables that can be used in the various templates, please refer to the [[Liquid Variable Reference]].
 
 
We sanitize all templates, so that you may not use javascript or tags that might be harmful to the application. Disallowed tags include, but aren’t limited to:
 
 
 
* HEAD
 
* BODY
 
* SCRIPT
 
 
 
=== Comments ===
 
 
 
HTML comments are automatically sanitized by our system. If you wish to place comments in your code, do it with a liquid comment, like so:
 
 
 
<pre> {{ # This is a comment in liquid, and won't show up on the output }} </pre>
 
 
 
=== Filters ===
 
 
 
Output markup takes filters. Filters are simple methods. The first parameter is always the output of the left side of the filter. The return value of the filter will be the new left value when the next filter is run. When there are no more filters the template will receive the resulting string.
 
 
 
<pre>
 
Hello {{ 'fred' | upcase }}
 
Hello fred has {{ 'fred' | length }} letters!
 
Hello {{ '*fred*' | textilize | upcase }}
 
Hello {{ 'now' | date: "%Y %h" }}
 
</pre>
 
 
 
=== Filter Reference ===
 
 
 
<html><style type="text/css">table.reference th {background-color: #EEEEEE;padding: 0px 4px;text-align: left;vertical-align: top;}</style></html>
 
{| class="reference"
 
!adjust_brightness(colour, percent)
 
|Returns a new colour with the brightness adjusted by the specified percentage. Negative percentages will darken the colour; positive percentages will brighten the colour.<br/><pre>{{ settings.btn_colour | adjust_brightness: -20 }}</pre>
 
|-
 
!adjust_hue(colour, percent)
 
|Returns a new colour with the hue adjusted by the specified percentage. Negative percentages will reduce the hue; positive percentages will increase the hue.<br/><pre>{{ settings.btn_colour | adjust_hue: 15 }}</pre>
 
|-
 
!adjust_saturation(colour, percent)
 
|Returns a new colour with the saturation adjusted by the specified percentage. Negative percentages will reduce the saturation; positive percentages will increase the saturation.<br/><pre>{{ settings.btn_colour | adjust_saturation: -35 }}</pre>
 
|-
 
!append(input, string)
 
|Add a string to the beginning of another string.
 
<pre>{{ 'This is first' | append: ' and this is last' }}</pre>
 
|-
 
!asset_url(input)
 
|Returns the URL for an asset.
 
<pre>{{ 'shop.css' | asset_url }}</pre>
 
The above example returns the path plus filename of the specified file.  In
 
this case it could be something like:
 
<pre>"http://asset2.spiffyserver.com/sites/3457/shop.css"</pre>
 
You will most probably use this URL with another filter to create a link or an
 
include tag for instance:
 
<pre>{{ 'shop.css' | asset_url | stylesheet_tag }}</pre>
 
|-
 
!capitalize(input)
 
|Capitalize all words in the input string.
 
<pre>{{ variant.title | capitalize }}</pre>
 
|-
 
!darken_by(colour, percent)
 
|Mix the RGB hue of the colour with Black so that the RGB hue is the specified percentage of the resulting colour.<br/><pre>{{ settings.btn_colour | darken_by: 20 }}</pre>
 
|-
 
!date(input, format)
 
|Reformat a date using an optional format string. Please see below for a list of the valid format characters.
 
<pre>%a - The abbreviated weekday name ("Sun")
 
%A - The full weekday name ("Sunday")
 
%b - The abbreviated month name ("Jan")
 
%B - The full month name ("January")
 
%c - The preferred local date and time representation
 
%d - Day of the month (01..31)
 
%H - Hour of the day, 24-hour clock (00..23)
 
%I - Hour of the day, 12-hour clock (01..12)
 
%j - Day of the year (001..366)
 
%m - Month of the year (01..12)
 
%M - Minute of the hour (00..59)
 
%p - Meridian indicator ("AM"  or  "PM")
 
%S - Second of the minute (00..60)
 
%U - Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)
 
%W - Week number of the current year, starting with the first Monday as the first day of the first week (00..53)
 
%w - Day of the week (Sunday is 0, 0..6)
 
%x - Preferred representation for the date alone, no time
 
%X - Preferred representation for the time alone, no date
 
%y - Year without a century (00..99)
 
%Y - Year with century
 
%Z - Time zone name
 
%% - Literal "%" character</pre>
 
<pre>{{ order_date | date: "%m %B, %Y" }}</pre>
 
|-
 
!default_pagination(paginate)
 
|This filter is to be used in conjunction with the [[Liquid Paginate Tag]].
 
It will produce default pagination for the paginated collection if you pipe in the paginate hash which is created by the [[Liquid Paginate Tag | paginate]] tag.
 
<pre><div id="paginate">{{ paginate | default_pagination }}</div></pre>
 
|-
 
!divided_by(input, operand)
 
|Perform division operation.
 
<pre>{{ 12 | divided_by: 3 }} => '4'
 
{{ 14 | divided_by: 3 }} => '4'
 
{{ 15 | divided_by: 3 }} => '5'</pre>
 
|-
 
!downcase(input)
 
|Convert a string to lower case.
 
<pre>{{ variant.title | downcase }}</pre>
 
|-
 
!escape(input)
 
|Escape a string so that all special characters are converted to their % form and can be recognised by browsers.
 
This may also be aliased as "h".
 
<pre>{{ product.url | escape }}</pre>
 
|-
 
!escape_javascript(input)
 
|Escape a string so that carriage returns and single and double quotes are escaped for use in Javascript segments..
 
<pre><a href="..." ... onmouseover="Tip('{{ item.title | escape_javascript }}')" ...></pre>
 
|-
 
!file_asset_url(input)
 
|Returns the URL for an uploaded file asset.
 
<pre>{{ 'catalog.pdf' | file_asset_url }}</pre>
 
The above example returns the path plus filename of the specified file.  In
 
this case it could be something like:
 
<pre>"http://asset2.spiffyserver.com/sites/3457/files/catalog.pdf"</pre>
 
|-
 
!first(array)
 
|Get the first element of an array.
 
<pre>{{ product.images | first | to_img }}</pre>
 
|-
 
!global_asset_url(input)
 
|Returns the URL for a global asset.
 
Global assets are kept in a certain directory on the Spiffy Stores web servers which is aggressively cached and compressed. Using assets from this global directory can improve the loading times of your pages dramatically. Here's a complete listing of all the global assets available:
 
<pre>{{ 'prototype.js' | global_asset_url | script_tag }}
 
{{ 'builder.js' | global_asset_url | script_tag }}
 
{{ 'controls.js' | global_asset_url | script_tag }}
 
{{ 'dragdrop.js' | global_asset_url | script_tag }}
 
{{ 'effects.js' | global_asset_url | script_tag }}
 
{{ 'scriptaculous.js' | global_asset_url | script_tag }}
 
{{ 'slider.js' | global_asset_url | script_tag }}
 
{{ 'sound.js' | global_asset_url | script_tag }}</pre>
 
<pre>{{ 'lightbox.css' | global_asset_url | stylesheet_tag }}
 
{{ 'lightbox.js' | global_asset_url | script_tag }}</pre>
 
<pre>{{ 'lightbox/v1/lightbox.css' | global_asset_url | stylesheet_tag }}
 
{{ 'lightbox/v1/lightbox.js' | global_asset_url | script_tag }}</pre>
 
<pre>{{ 'lightbox/v2/lightbox.css' | global_asset_url | stylesheet_tag }}
 
{{ 'lightbox/v2/lightbox.js' | global_asset_url | script_tag }}</pre>
 
|-
 
!highlight_active_tag(tag, css_class='active')
 
|This filter creates a span with the class ''active'' around the tag if it is active. An active tag means that it is currently used to narrow down the selection of displayed  products in a given collection. A tag becomes active when someone clicks on a tag link generated by a ''link_to_tag'' or ''link_to_add_tag'' filter.
 
<pre>{% for tag in collection.tags %}
 
  {{ tag | highlight_active_tag | link_to_tag: tag }}
 
{% endfor %}</pre>
 
|-
 
!img_tag(url, alt="")
 
|This filter creates an image tag, using the ''url'' parameter as image source (<img src="...>) and an optional second parameter as an ''alt'' description of the image.
 
<pre>{{ 'image_name.jpg' | image_tag }}</pre>
 
|-
 
!join(input, glue = ' ')
 
|Join elements of an array with an optional join character, which defaults to a space.<br/><pre>{{ names | join: ',' }}</pre>
 
|-
 
!last(array)
 
|Get the last element of an array.<br/><pre>{{ product.images | last | to_img }}</pre>
 
|-
 
!lighten_by(colour, percent)
 
|Mix the RGB hue of the colour with White so that the RGB hue is the specified percentage of the resulting colour.<br/><pre>{{ settings.btn_colour | lighten_by: 20 }}</pre>
 
|-
 
!link_to(link, url, title="")
 
|A ''link_to filter'' creates a link (<a href="...>) for the given parameters. The first parameter is the link name, the second is the ''url'' and the third parameter specifies an optional title.
 
<pre> {{ 'Spiffy Stores' | link_to: 'http://www.spiffystores.com.au', 'The best shopping cart on the planet' }}</pre>
 
|-
 
!link_to_add_tag(label, tag)
 
|This filter creates a link to all products in a collection that have the given tag including and all the previous tags that might have been added.
 
<pre>{% for tag in collection.tags %}
 
  {{ '+' | link_to_add_tag: tag }} {{ tag }}
 
{% endfor %}</pre>
 
The above code creates a list of links for each tag for each product in the collection. In this case, the '+' is the clickable link name followed by a tag name. Using this filter, you can specify the search by using more than just one tag. For example,  you can add the tags "green", "summer sale" and "cheap" within a collection called "clothing" and it would show you only products that are in this collection that also have all of the added tags.
 
|-
 
!link_to_remove_tag(label, tag)
 
|This filter creates a link to all products in a collection with the given tag removed, but maintaining all of the previous tags that have been added.
 
<pre>{% for tag in collection.tags %}
 
  {{ '-' | link_to_remove_tag: tag }} {{ tag }}
 
{% endfor %}</pre>
 
|-
 
!link_to_tag(label, tag, all=false)
 
|This filter creates a link to all products in a collection that have the given tag.<br/><pre>{% for tag in collection.tags %}
 
  {{ tag | link_to_tag: tag }}
 
{% endfor %}</pre><br/>The above code creates a list of links for each tag for each product in the collection. Each link will show all of the products in the collection that are tagged with the corresponding tag.
 
|-
 
!link_to_type(type)
 
|This filter creates a link to all items in the collection matching the given ''type''.<br/><pre>{{ "Shirt" | link_to_type }}</pre><br/>In this example, a link would be created called "Shirt" which links to all products of the type ''Shirt''.
 
|-
 
!link_to_vendor(vendor)
 
|This filter creates a link to all items in the collection matching the given ''vendor''.<br/><pre>{{ "Spiffy" | link_to_vendor }}</pre><br/>In this example, a link would be created called "Spiffy" which links to all products belonging to the vendor ''Spiffy''.
 
|-
 
!map(input, property)
 
|Select the elements of an array of hashes or drops using the specified property.
 
<pre>{{ names | map: 'last_name' }}</pre>
 
|-
 
!minus(input, operand)
 
|Perform minus operation.
 
<pre>{{ 5 | minus: 1 }} => '4'</pre>
 
|-
 
!money(money)
 
|This filter takes a number and converts it to a string formatted based on your store currency format, which is selected from the General Preferences screen.<br/><pre>{{ 1.45 | money }}</pre><br/>By default, using AUD as the currency, this would be formatted as<br/><pre>$1.45</pre>
 
|-
 
!money_rounded(money)
 
|This filter takes a number and rounds it to an integer number.<br/><pre>{{ 1.45 | money_rounded }}</pre><br/>In this example, this will be formatted as
 
<br/><pre>1</pre>
 
|-
 
!money_with_currency(money)
 
|This filter takes a number and converts it to a string formatted based on your store currency format, which is selected from the General Preferences screen.<br/><pre>{{ 1.45 | money_with_currency }}</pre><br/>By default, using AUD as the currency, this would be formatted as<br/><pre>$1.45 AUD</pre>
 
|-
 
!money_without_currency(money)
 
|This filter takes a number and returns it formatted to 2 decimal places.<br/><pre>{{ 1.45 | money_without_currency }}</pre><br/>In this example, this will be formatted as<br/><pre>1.45</pre>
 
|-
 
!newline_to_br(input)
 
|Add <nowiki><br /></nowiki> tags to the beginning of all lines in the input string.<br/><pre>{{ output_lines | newline_to_br }}</pre>
 
|-
 
!pluralize(input, singular, plural)
 
|This filter accepts a number, and two words - one for singular, one for plural and returns the singular word if the input equals 1, otherwise it returns the plural.
 
<pre>You have {{ cart.item_count }} {{ cart.item_count | pluralize: 'item', 'items' }} in your shopping cart.</pre>
 
|-
 
!plus(input, operand)
 
|Perform plus operation.<br/><pre>{{ 1 | plus: 1 }} => '2'
 
{{ '1' | plus:'1' }} => '11'</pre>
 
|-
 
!prepend(input, string)
 
|Add a string to the end of another string.
 
<pre>{{ ' and this is last' | prepend: 'This is first' }}</pre>
 
|-
 
!product_img_url(url, style = 'small')
 
|This filter takes a ''url'' of a product's image filename and returns its full path. It takes an optional second parameter to set its size and returns the URL of the small sized version of the image by default.
 
 
 
Available Sizes
 
* pico (16x16)
 
* icon (32x32)
 
* thumb (50x50)
 
* small (100x100)
 
* medium (240x240)
 
* large (480x480)
 
* original - No resizing, but maximum size is 800x600.
 
* custom1 - Custom size configured by the Theme Editor
 
* custom2  - Custom size configured by the Theme Editor
 
*custom3  - Custom size configured by the Theme Editor
 
 
 
These are the maximum images sizes, and all images are resized to maintain the original aspect ratio, so rectangular images will have one dimension that is less than the maximum size for that image size.
 
<pre><a href="{{product.url}}"><img src="{{ product.featured_image | product_img_url: 'thumb' }}" /></a></pre>
 
|-
 
!remove(input, string)
 
|Remove all occurrences of a string.
 
<pre>{{ 'This is a test' | remove: 'is a' }}</pre>
 
|-
 
!remove_first(input, string)
 
|Remove the first occurrence of a string.
 
<pre>{{ 'This is a test' | remove_first: 'is' }}</pre>
 
|-
 
!replace(input, string, replacement = '')
 
|Replace all occurrences of a string with another.
 
<pre>{{ 'This is a test' | replace: 'a', 'my' }}</pre>
 
|-
 
!replace_first(input, string, replacement = '')
 
|Replace the first occurrence of a string with another.
 
<pre>{{ 'This is a test' | replace_first: 'is', 'at' }}</pre>
 
|-
 
!script_tag(url)
 
|This filter takes a URL with a .js file and puts a script tag around it. Use this filter in the page header for all your javascript files.
 
<pre>{{ 'shop.js' | asset_url | script_tag }}</pre>
 
|-
 
!size(input)
 
|Return the size of an array or of a string.<br/><pre>{{ variant.title | size }}</pre>
 
|-
 
!sort(input, property = nil)
 
|Sorts the elements in an array. An optional property can be specified to be used to sort an array of hashes or drops.
 
<pre>{{ names | sort | join: ',' ) }}</pre>
 
|-
 
!strip_html(input)
 
|Strip out any html tags. This is a simple filter which removes any characters in the form of an HTML tag, such as "<...>". This can be useful in combination with truncate, to generate fragment summaries of formatted text.<br/><pre>{{ 'my long<br>string' | strip_html }}</pre>
 
|-
 
!strip_newlines(input)
 
|Remove all new lines from the string.
 
|-
 
!stylesheet_tag(url, media="all")
 
|This filter takes a URL with a .css file and puts a link tag around it. Use this filter in the page header for all your stylesheet files.
 
<pre>{{ 'shop.css' | asset_url | stylesheet_tag }}</pre>
 
|-
 
!times(input, operand)
 
|Perform times operation.
 
<pre>{{ 3 | times: 4 }} => '12'
 
{{ 'foo' | times: 4 }} => 'foofoofoofoo'</pre>
 
|-
 
!truncate(input, length = 50, truncate_string = "...")
 
|Truncate a string down to x characters. Additionally, a character string can be specified to indicate that truncation has occurred.<br/><pre>{{ 'my long string' | truncate: 50, '...' }}</pre>
 
|-
 
!truncatewords(input, words = 15, truncate_string = "...")
 
|Truncate a string down to a number of words. This is the same as "truncate", except that the length is specified in words, rather than characters.<br/><pre>{{ 'my long string' | truncatewords: 2, '...' }}</pre>
 
|-
 
!unescape(input)
 
|Unescape a string so that all special characters are converted from their % form into their original characters..
 
<pre>{{ encoded_string | unescape }}</pre>
 
|-
 
!upcase(input)
 
|Convert a string to upper case.<br/><pre>{{ variant.title | upcase }}</pre>
 
|-
 
!url_encode(input)
 
|** TODO ** This appears to be the same function as escape.
 
|-
 
!url_for_type(type_title)
 
|This filter creates a valid URL for a type name.
 
|-
 
!url_for_vendor(vendor_title)
 
|This filter creates a valid URL for a vendor name.
 
|-
 
!weight(grams)
 
|This filter takes a weight in grams and converts it into the appropriate unit system ( metric, imperial ) for the shop. The unit of weight is not displayed. All weights are stored internally in grams so you should always use this filter when displaying weights to clients.
 
<pre>{{ product.weight | weight }}</pre>
 
|-
 
!weight_with_unit(grams)
 
|This filter takes a weight in grams and converts it into the appropriate unit system ( metric, imperial ) for the shop. All weights are stored internally in grams so you should always use this filter when displaying weights to clients.
 
<pre>{{ product.weight | weight_with_unit }}</pre>
 
|-
 
!within(product_url, collection)
 
|This filter is used to indicate that the filtered URL of a passed in object belongs to a specified collection.
 
<pre>{{product.url | within: collection }}</pre>
 
There is further discussion on this filter in [[Liquid Collection Navigation ]].
 
|}
 
  
 
== Tags ==
 
== Tags ==
  
Tags are for the logic in your template.
+
For a full description on all the Liquid tags, please refer to the [[Liquid Tag Reference]].
  
=== Comments ===
+
== Acceptable Tags and Comments ==
  
A comment is the simplest of tags. It just swallows content.
+
All templates are sanitized, so you may not use JavaScript or tags that might be harmful to the application. Disallowed tags include, but aren’t limited to:
 
 
<pre>
 
Hi fred {% comment %} you stink {% endcomment %}
 
</pre>
 
  
=== Variable Assignment ===
+
* <code><nowiki><HEAD></nowiki></code>
 +
* <code><nowiki><BODY></nowiki></code>
 +
* <code><nowiki><SCRIPT></nowiki></code>
  
You can store data in your own variables, to be used in output or other tags as desired.
+
== Comments ==
  
The simplest way to create a variable is with the '''assign''' tag, which has a pretty straightforward syntax:
+
HTML comments are automatically sanitized, so if you wish to place comments in your code, do it with a Liquid comment.
  
 
<pre>
 
<pre>
{% assign name = 'freestyle' %}
+
{{ # This is a comment in Liquid, and won't show up on the output }}
{% for t in collections.tags %}{% if t == name %}
 
  <p>Freestyle!</p>
 
{% endif %}{% endfor %}
 
 
</pre>
 
</pre>
  
Another way of doing this would be to assign true/false values to the variable:
+
== Filters ==
  
<pre>
+
Within the '''Output''' blocks, you can add filters that modify the results of the output block. The filters can be chained together, with the output from one filter being passed as input to the next. A filter is a small piece of code that performs some simple transformation.
{% assign freestyle = false %}
 
{% for t in collections.tags %}{% if t == 'freestyle' %}
 
  {% assign freestyle = true %}
 
{% endif %}{% endfor %}
 
{% if freestyle %}
 
  <p>Freestyle!</p>
 
{% endif %}
 
</pre>
 
  
If you want to combine a number of strings into a single string and save it to a variable, you can do that with the '''capture''' tag. This tag is a block which "captures" whatever is rendered inside it and assigns it to the given variable instead of rendering it to the screen. Here's how it works:
+
When filters are chained together, the first parameter is always the output of the left side of the filter. The return value of the filter will be the new left value when the next filter is run. When there are no more filters the template will receive the resulting string.
  
 
<pre>
 
<pre>
  {% capture attribute_name %}{{ item.title }}-{{ i }}-color{% endcapture %}
+
Hello {{ 'fred' | upcase }}
 
+
Hello fred has {{ 'fred' | length }} letters!
  <label for="{{ attribute_name }}">Colour:</label>
+
Hello {{ '*fred*' | textilize | upcase }}
  <select name="attributes[{{ attribute_name }}]" id="{{ attribute_name }}">
+
Hello {{ 'now' | date: "%Y %h" }}
    <option value="red">Red</option>
 
    <option value="green">Green</option>
 
    <option value="blue">Blue</option>
 
  </select>
 
 
</pre>
 
</pre>
  
=== Arrays ===
+
For a full description of all the Liquid filters, please refer to the [[Liquid Filter Reference]].
  
If a liquid expression returns an array of objects, then you can access the members of the array using an index notation.
+
== Filtered Expressions ==
  
For example to access the third element of an array of products
+
Filtered expressions can also be used in expressions in the following tags
<pre>
 
{{ collection.products[2].title }}
 
</pre>
 
  
All array elements are accessed using a zero-based index, so the first element of the array is always index 0.
+
* Assign
  
Additionally, three special methods are available for arrays.
+
Here is an example:
<pre>
 
'size' - Returns the number of elements in the array
 
'first' - Returns the first element in the array
 
'last' - Returns the last element in the array
 
</pre>
 
  
 
<pre>
 
<pre>
{{ collection.products.first }}
+
{% assign prefix = product.title | substring: 0, 3 | upcase %}
{{ collection.products.last }}
 
You have {{ cart.items.size }} items in your cart
 
 
</pre>
 
</pre>
  
=== If / Else ===
+
== Further Reference ==
 
 
The conditional expressions formed with '''If/Else''' should be a familiar construction from most programming languages. Liquid allows you to write simple expressions in the '''if'''.
 
  
The conditions that can be used to test for logical conditions are:
+
* [[Liquid Tag Reference]]
<pre>
+
* [[Liquid Variable Reference]]
'==' - Equal
+
* [[Liquid Filter Reference]]
'!=' - Not Equal
+
* [[Liquid Paginate Tag|Pagination ]]
'<>' - Not Equal
 
'<' - Less Than
 
'>' - Greater Than
 
'>=' - Greater Than or Equal
 
'<=' - Less Than or Equal
 
'contains' - String contains substring
 
</pre>
 
 
 
Compound expressions may be formed by the use of '''or''' and '''and''' expressions.
 
 
 
<pre>
 
{% if user %}
 
  Hi {{ user.name }}
 
{% endif %}
 
 
 
{% if user.name == 'fred' %}
 
  hi fred
 
{% endif %}
 
 
 
{% if user.name != 'fred' %}
 
  you aren't fred
 
{% endif %}
 
 
 
{% if user.name == 'fred' or user.name == 'dirk' %}
 
  hi dirk or fred
 
{% endif %}
 
 
 
{% if user.name == 'fred' and user.last_name == 'bloggs' %}
 
  hi fred bloggs
 
{% endif %}
 
 
 
{% if user.creditcard == null %}
 
  user has no credit
 
{% endif %}
 
 
 
{% if user.payments == empty %}
 
  you never paid !
 
{% endif %}
 
 
 
{% if user.age > 18 %}
 
  Login here
 
{% else %}
 
  Sorry, you are too young
 
{% endif %}
 
 
 
{% if user.name contains 'y' %}
 
  Sorry, we don't allow users with a 'y' in their name! 
 
{% endif %}
 
</pre>
 
 
 
=== IfChanged Block ===
 
 
 
The '''ifchanged''' block tag is used within a loop. It checks its own rendered contents against its previous state and only displays its content if the value has changed.
 
 
 
For example, in order to show the date only when a post is published on a new day (always displaying the time):
 
 
 
<pre>
 
{% ifchanged %}
 
  <div class="date">{{ article.published_at | date: '%B %d'  }}</div>
 
{% endifchanged %}
 
<div class="time">{{ article.published_at | date: '%I:%M %p'  }}</div>
 
</pre>
 
 
 
=== Case Statement ===
 
 
 
If you need more than one condition you can use the '''Case''' statement
 
 
 
<pre>
 
{% case line_item.quantity %}
 
  {% when 0 %}
 
  none
 
  {% when 1 %}
 
  one
 
  {% when 2 %}
 
  two
 
  {% else %}
 
  a few more...
 
{% endcase %}
 
</pre>
 
 
 
'''Example:'''
 
<pre>
 
{% case template %}
 
 
{% when 'label' %}
 
    // {{ label.title }}
 
{% when 'product' %}
 
    // {{ product.vendor | link_to_vendor }} / {{ product.title }}
 
{% else %}
 
    // {{page_title}
 
{% endcase %}
 
</pre>
 
 
 
=== Cycle ===
 
 
 
Often you have to cycle through an number of alternative values. Liquid has built-in support for such operations using the '''Cycle''' tag.
 
 
 
<pre>
 
{% cycle 'one', 'two', 'three' %}
 
{% cycle 'one', 'two', 'three' %}
 
{% cycle 'one', 'two', 'three' %}
 
{% cycle 'one', 'two', 'three' %}
 
</pre>
 
 
 
''...will result in...''
 
 
 
<pre>
 
one
 
two
 
three
 
one
 
</pre>
 
 
 
If no name is supplied for the cycle group then its assumed that multiple calls with the same parameters are one group.
 
 
 
If you want to have total control over cycle groups you can optionally specify the name of the group. This can even be a variable.
 
 
 
<pre>
 
{% cycle 'group 1': 'one', 'two', 'three' %}
 
{% cycle 'group 1': 'one', 'two', 'three' %}
 
{% cycle 'group 2': 'one', 'two', 'three' %}
 
{% cycle 'group 2': 'one', 'two', 'three' %}
 
</pre>
 
 
 
''...will result in...''
 
 
 
<pre>
 
one
 
two
 
one
 
two
 
</pre>
 
 
 
=== For Loops ===
 
 
 
Liquid allows for loops over collections. This allows you to loop over things like line-items in an order.
 
 
 
<pre>
 
  {% for item in order.line-items %}
 
    {{ item.description }}
 
  {% endfor %}
 
</pre>
 
 
 
The order of the loop may be reversed by adding the flag ''reversed''.
 
 
 
<pre>
 
  {% for item in order.line-items reversed %}
 
    {{ item.description }}
 
  {% endfor %}
 
</pre>
 
 
 
During every '''For''' loop, the following helper variables are available for additional control over the results.
 
 
 
<pre>
 
forloop.length    # => length of the entire for loop
 
forloop.index      # => index of the current iteration
 
forloop.index0    # => index of the current iteration (zero based)
 
forloop.rindex    # => how many items are still left?
 
forloop.rindex0    # => how many items are still left? (zero based)
 
forloop.odd        # => is this iteration odd (zero based)?
 
forloop.even      # => is this iteration even (zero based)?
 
forloop.first      # => is this the first iteration?
 
forloop.last      # => is this the last iteration?
 
</pre>
 
 
 
There are several attributes you can use to influence which items you receive in your loop
 
 
 
*'''limit''' lets you restrict how many items you get
 
*'''offset''' lets you start the collection with the nth item.
 
 
 
<pre>
 
  # array = [1,2,3,4,5,6]
 
  {% for item in array limit:2 offset:2 %}
 
    {{ item }}
 
  {% endfor %}
 
  # results in 3,4
 
</pre>
 
 
 
Instead of looping over an existing collection, you can define a range of numbers to loop through. The range can be defined by both literal and variable numbers:
 
 
 
<pre>
 
  # if item.quantity is 4...
 
  {% for i in (1..item.quantity) %}
 
    {{ i }}
 
  {% endfor %}
 
  # results in 1,2,3,4
 
</pre>
 
 
 
=== Tables ===
 
 
 
Liquid can also create table rows and cells for you, although you still need to wrap a table tag around the '''tablerow''' tag.
 
 
 
<pre>
 
  <table>
 
    {% tablerow item in items cols: 3 limit: 12 %}
 
      {{ item.variable }}
 
    {% endtablerow %}
 
  </table>
 
</pre>
 
 
 
You can also find out whether a table cell is the first or last column in a row or directly query the column number.
 
 
 
<pre>
 
tablerowloop.length      # => length of the entire for loop
 
tablerowloop.index        # => index of the current iteration
 
tablerowloop.index0      # => index of the current iteration (zero based)
 
tablerowloop.rindex      # => how many items are still left?
 
tablerowloop.rindex0      # => how many items are still left? (zero based)
 
tablerowloop.first        # => is this the first iteration?
 
tablerowloop.last        # => is this the last iteration?
 
tablerowloop.odd          # => is this iteration odd (zero based)?
 
tablerowloop.even        # => is this iteration even (zero based)?
 
tablerowloop.col          # => index of column in the current row
 
tablerowloop.col0        # => index of column in the current row (zero based)
 
tablerowloop.col_first    # => is this the first column in the row?
 
tablerowloop.col_last    # => is this the last column in the row?
 
</pre>
 
 
 
<pre>
 
  {% tablerow item in items cols: 3 %}
 
    {% if col_first %}
 
      First column: {{ item.variable }}
 
    {% else %}
 
      Different column: {{ item.variable }}
 
    {% endif %}
 
  {% endtablerow %}
 
</pre>
 

Latest revision as of 16:38, 11 January 2016

Spiffy Stores gives you 100% control over the HTML and CSS for your online storefront. Our themes use standard HTML and CSS, with dynamic tags from a templating language called "Liquid" to display dynamic data. This helps you transform your design into a dynamic e-commerce web site as quickly as possible.

This is an introduction to the Spiffy Stores Liquid template syntax, and a reference for Spiffy Stores-specific Tags and Filters.

Liquid is the templating engine for customizing your store layout. It's a small and fast template language which is quick and easy to learn but contains very powerful features for full customization.

You can use a template language such as Liquid to substitute variable data into a page layout. For example, each product page is defined by the product.liquid template. This file contains the HTML that describes the layout of the various elements on a product page. Within this template, you will find various Liquid tags and variables that help to display different data for each product.

For example, a product template will usually contain a product title, using the {{ product.title }} Liquid variable. A different title will be used for each different product that is displayed, as the Liquid variable is substituted for the actual product title.

Basics

There are two types of markup in liquid: Output and Tag.

  • Output is surrounded by - {{ two curly brackets }}
  • Tags are surrounded by - {% a curly bracket and a percent %}

Output blocks will always be replaced with the data which they reference.

For instance if your liquid template has a product object exposed to it you can print the name of the product to the screen by referencing {{ product.title }}

Tags allow you to control the logic of templates. They are responsible for loops and branching logic such as If / Else.

Output

Here is a simple example of Output. The Liquid code contains variables that will be replaced by the actual values when the template is rendered.

Hello {{ name }}
Hello {{ user.name }}
Hello {{ 'fred' }}

For a full description of all the Liquid variables that can be used in the various templates, please refer to the Liquid Variable Reference.

Tags

For a full description on all the Liquid tags, please refer to the Liquid Tag Reference.

Acceptable Tags and Comments

All templates are sanitized, so you may not use JavaScript or tags that might be harmful to the application. Disallowed tags include, but aren’t limited to:

  • <HEAD>
  • <BODY>
  • <SCRIPT>

Comments

HTML comments are automatically sanitized, so if you wish to place comments in your code, do it with a Liquid comment.

{{ # This is a comment in Liquid, and won't show up on the output }}

Filters

Within the Output blocks, you can add filters that modify the results of the output block. The filters can be chained together, with the output from one filter being passed as input to the next. A filter is a small piece of code that performs some simple transformation.

When filters are chained together, the first parameter is always the output of the left side of the filter. The return value of the filter will be the new left value when the next filter is run. When there are no more filters the template will receive the resulting string.

Hello {{ 'fred' | upcase }}
Hello fred has {{ 'fred' | length }} letters!
Hello {{ '*fred*' | textilize | upcase }}
Hello {{ 'now' | date: "%Y %h" }}

For a full description of all the Liquid filters, please refer to the Liquid Filter Reference.

Filtered Expressions

Filtered expressions can also be used in expressions in the following tags

  • Assign

Here is an example:

{% assign prefix = product.title | substring: 0, 3 | upcase %}

Further Reference