https://bl.ocks.org/roachhd/2909c695979764498922

full-on

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

{ { matched pairs of curly brackets (ie, braces) } }
{ % matched pairs of curly brackets and percent signs %}

Output

Here is a simple example of Output:

Hello 
Hello 
Hello tobi

Advanced output: 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.

Hello TOBI
Hello tobi has 4 letters!
Hello *TOBI*
Hello 2020 Oct

Standard Filters

Tags

Tags are used for the logic in your template. New tags are very easy to code, so I hope to get many contributions to the standard tag library after releasing this code.

Here is a list of currently supported tags:

Comments

Comment is the simplest tag. It just swallows content.

We made 1 million dollars  this year

Raw

Raw temporarily disables tag processing. This is useful for generating content (eg, Mustache, Handlebars) which uses conflicting syntax.


  In Handlebars, {{ this }} will be HTML-escaped, but {{{ that }}} will not.

If / Else

if / else should be well-known from any other programming language. Liquid allows you to write simple expressions in the if or unless (and optionally, elsif and else) clause:


# Same as above





  Hello non-tobi

# Same as above

  Hello non-tobi

# Check for the size of an array




   Sorry, you are too young

# array = 1,2,3

# string = 'hello world'

Case Statement

If you need more conditions, you can use the case statement:


... else ...

Example:


     // 

Cycle

Often you have to alternate between different colors or similar tasks. Liquid has built-in support for such operations, using the cycle tag.

one
two
three
one

will result in

one
two
three
one

If no name is supplied for the cycle group, then it’s 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.

one
two
one
two

will result in

one
two
one
two

For loops

Liquid allows for loops over collections:


When iterating a hash, item[0] contains the key, and item[1] contains the value:


During every for loop, the following helper variables are available for extra styling needs:

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.first       # => is this the first iteration?
forloop.last        # => is this the last iteration?

There are several attributes you can use to influence which items you receive in your loop

limit:int lets you restrict how many items you get. offset:int lets you start the collection with the nth item.

# array = [1,2,3,4,5,6]

# results in 3,4

Reversing the loop


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:

# if item.quantity is 4...

# results in 1,2,3,4

Variable Assignment

You can store data in your own variables, to be used in output or other tags as desired. The simplest way to create a variable is with the assign tag, which has a pretty straightforward syntax:




Another way of doing this would be to assign true / false values to the variable:






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, then assigns the captured value to the given variable instead of rendering it to the screen.

  

  <label for="--color">Color:</label>
  <select name="attributes[--color]" id="--color">
    <option value="red">Red</option>
    <option value="green">Green</option>
    <option value="blue">Blue</option>
  </select>

HACK-IT

First steps

It’s very simple to get started with Liquid. A Liquid template is rendered in two steps: Parse and Render. For an overview of the Liquid syntax, please read [[Liquid for Designers]].

@template = Liquid::Template.parse("hi freestyle")  # Parses and compiles the template
@template.render( 'name' => 'tobi' )               # Renders the output => "hi tobi"

The parse step creates a fully compiled template which can be re-used as often as you like. You can store it in memory or in a cache for faster rendering later.

All parameters you want Liquid to work with have to be passed as parameters to the render method. Liquid does not know about your Ruby local, instance, and global variables.

Extending Liquid

Extending Liquid is very easy. However, keep in mind that Liquid is a young library and requires some outside help. If you create useful filters and tags, please consider making a pull request with them.

Create your own filters

Creating filters is very easy. Basically, they are just methods which take one parameter and return a modified string. You can use your own filters by passing an array of modules to the render call like this: @template.render(assigns, [MyTextFilters, MyDateFilters]).

module TextFilter
  def textilize(input)
    RedCloth.new(input).to_html
  end
end
@template = Liquid::Template.parse(" *hi* ")
@template.render({}, :filters => [TextFilter])              # => "<strong>hi</strong>"

Alternatively, you can register your filters globally:

module TextFilter
  def textilize(input)
    RedCloth.new(input).to_html
  end
end

Liquid::Template.register_filter(TextFilter)

Once the filter is globally registered, you can simply use it:

@template = Liquid::Template.parse(" *hi* ")
@template.render              # => "<b>hi</b>"

Create your own tags

To create a new tag, simply inherit from Liquid::Tag and register your block with Liquid::Template.

class Random < Liquid::Tag
  def initialize(tag_name, max, tokens)
     super
     @max = max.to_i
  end

  def render(context)
    rand (@max).to_s
  end
end

Liquid::Template.register_tag('random', Random)
@template = Liquid::Template.parse(" { % random 5 %}")
@template.render    # => "3"

Create your own tag blocks

All tag blocks are parsed by Liquid. To create a new block, you just have to inherit from Liquid::Block and register your block with Liquid::Template.

class Random < Liquid::Block
  def initialize(tag_name, markup, tokens)
     super
     @rand = markup.to_i
  end

  def render(context)
    value = rand(@rand)
    super.sub('^^^', value.to_s)  # calling `super` returns the content of the block
  end
end

Liquid::Template.register_tag('random', Random)
text = " { % random 5 %} you have drawn number ^^^, lucky you! { % endrandom %} "
@template = Liquid::Template.parse(text)
@template.render  # will return "you have drawn number 1, lucky you!" in 20% of cases