By Daniel Cooper

Ditching ERB: A Guide to Using Liquid

By Daniel Cooper
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

The view layer in a traditional Rails app hasn’t changed a huge amount since rails 1.0 was shipped back in the crazy mid noughties. Sure—you might have switched from Prototype to jQuery, XHTML to HTML5, CSS to slightly nicer responsive CSS—but the thing that’s always driven it all has been our good friend ERB. Perhaps it’s time for a change?

But, what’s wrong with ERB?

ERB is great for certain types of apps—but it does have some shortcomings, both aesthetic and practical.

Full Ruby

What’s the saying? ‘With great power comes terrible separation of concerns.’ ERB pretty much gives you access to the full the complete and terrifying power of Ruby. The temptation will always be close to flirt with models and libraries which have no business being called in view code. Sure, just once isn’t a crime but the temptation is there and so is the slippery slope.

Also, being able to execute arbitrary code in your views means your view layer is stuck in—house. You won’t be able to let outside folk create themes for your app (if that’s a thing you’d like to them to do) because they’re only a back tick and badly set up server away from causing some real damage, should you have a falling out with them.

Things could be nicer

If there’s one thing that’s true about the Ruby community—perhaps to a fault sometimes—is that there’s a general desire for code to be beautiful. ERB isn’t beautiful, but some efforts like Moustache and HAML allow much of the power of ERB while improving on the aesthetics.

Using Liquid

My preferred templating language is Liquid. Liquid was extracted from Shopify and powers their shop building efforts. My appreciation for liquid is two fold: First, it allows nice safe templates I can allow (power) users to edit in much the same way as Shopify does. Second, it forces a cleaner distinction between the data layer of your application and the presentation layer.

Getting started

As with most things Rails, installation is a breeze (head over to the Liquid homepage for up to date instructons).
Generally speaking, liquid templates are parsed and and then rendered with a context. The context, in most simple cases, need only be a Hash. When writing the template, each key in the hash becomes the name for variable with it’s value fully available to you. Substitutions for these keys can be made by using double curlys: {{x}}


One of the features that I love in liquid is filters. Filters behave in much the same way, and should be used for much the same purpose, as helpers in Rails. They’re short methods which aid in the presenting of information. Let’s take a look at how we can use filters.

As you might guess, this will output the string HELLOWORLD. There are a few things to remember here. Each pipe signifies that the output of the previous section will be passed to the next, so ‘world’ is passed to the prepend method with the additional argument hello which is in the passed to the method upcase—so we can get shouty.

Tags & blocks

Filters are great, but you’ll eventually want to perform some logic, like an if statement or a for loop. For that, we’ve got tags and blocks.
Tags, much like ERB, use an alternative syntax for logic sections: {%%}. This is best shown by example.


Extending liquid

So, that’s pretty much all you need to know to start using liquid for your templating needs. One of the awesome things about liquid, over the other similar templating engines, is how extendable it is.


Filters are pretty much just helpers. They take one or more arguments, the first of which is the value to the left of the pipe (|), additional arguments are passed one by one after this. Let’s take a look at the implementation of the truncate filter from the standard set.

The value of ‘sometext’ will be passed through as input while length and truncatestring are passed through in order.

Tags & blocks

Tags and blocks, as we’ve seen, provide extendibility beyond that of filters. To illustrate how useful blocks can be, we’ll write a block which allows our designer to process a specific twitter timeline and output it in any way he or she see’s fit. Usage will look something like:

The first step in creating a new block is to inherit from Liquid::Block and define a initializer. You’ll want to call super in your initializer on the first line, it’ll do a bunch of setup for you. The initializer takes three arguments.

  1. tag_name
  2. markup — the arguments passed to be block. In the usage example above, this would be the string source:
  3. tokens — a fully passed list of tokens. Unless your doing a fairly advanced tag that gets into the guts of liquid, you can ignore this.

Since we’ve got some arguments to process, namely the source of our RSS feed, we’ll need to do a bit of parsing. The Liquid Gem provides a Regex, Liquid::TagAttributes, which will help us process the above string and come out with a hash in the way you’d expect.

The actual rendering in a liquid block is done in the render method. The render method always takes one argument: context. The context is the current state of the rendering stack. All of your inputs and data live in this data structure.

We’re creating a block which is going to create temporary variables that’ll be used only in the context of the block. This behaves just like a block in ruby (if you’re calling each on an array, for example.) We can temporarily push to the stack by calling #stack on the context object and providing a block.

If you plan to have any output for your block-and in this case we definitely do—then the #render_all method is the key. It takes two arguments: a context and a node list. If you’ve called super in your initialiser then the nodelist will be provided as @nodelist.

So, put all these pieces together and you should come up with something like this:

You’ll almost certainly want to add some caching and error handling here—I’ve left it out for readability.

It’s worth remebering that the the arguments to this block will always come through as strings and as such you won’t be able to use variables to populate the source out of the box. But, no matter—the context (which you’ll remember is passed to the render method) provides all the variables the designer has been using. Somewhere in the render block you’ll be able to pull out the variable value like this:

Notice how we first check if the context has the appropriate key. We have to do this because we have no way of knowing if the token refers to a variable or is just a string. Alternatively, for this particular tag you could check if the source looks like a URL before inspecting the context.

Wrap up

And so, I hope you’ll agree Liquid is pretty neat. It’s a powerful and expressive templating langauge that does a great job at providing you (‘the programmer’) the tools to allow your designers to build excellent sites without the worry that they’ll rm -rf the whole thing. With luck, I’ve been clear—but if not I’ll be lurking around the comment section if you have any questions.

Login or Create Account to Comment
Login Create Account
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?