Ditching ERB: A Guide to Using Liquid

Tweet

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}}

Filters

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

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: http://www.sitepoint.com/feed/
  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.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Tristan

    This was a well written and informative article.

  • Tim

    This has to be the most one-sided, slanted, biased article on ERB I’ve seen in my career. How can you actually pan it like that when you obviously haven’t explored its capabilities thoroughly.

    I suggest you look at ERB with a magnifying glass good sir, and hopefully Rubysource will post a retraction for this sham of an article. I hope you didn’t pay this Cooper fellow for this guff.

    I expect better.

    • Jimothy

      Are you serious? Daniel has merely pointed out some shortcomings of ERB, and his preference for an alternative. And you’re demanding a retraction? I think you’re taking this way too personally.

  • Ed Allen

    You might want to look at how your page renders in Chrome. There’s a screenshot bit that is showing truncated text, starting with “iquid” trying to be a sort of subtitle to the article.

  • http://dogma.co.uk Richard Kimber

    Great article, one thing concerns me though. I use Handlebars.js for client-side templating which obviously uses a simular syntax. Is there anything in place to stop Liquid parsing Handlebars markup?

    Rich

  • Murillo

    I really didn’t see any advantages of Liquid over Erb.

  • Jig

    Everything’s fine, besides that it requires a patch to work well with Rails 3 and isn’t being actively developed.
    And if someone really tries to give users an opportunity to edit view templates, I would be interested to see how they expose the names and definitions of the variables available in template, as I haven’t found a way if not hardcoding everything.

  • http://14lines.com Daniel Cooper

    @jig The last commit on github was 3 days ago. I’m not sure what you’re objection to ‘hard coding’ variables is. You’ll be doing some work at the controller level and providing ways to get at that data in the view that the user can edit. Take a peak at the Shopify documentation (http://wiki.shopify.com/Article_variables). You’ll see that their usecase is “when you’re skinning a article page, you’ll get these article variables to work with”.

  • Jig

    @Daniel Please have a look at what a commit is that, just some typo, version update, some documentation update – nothing important. I won’t hide I’m a bit dissapointed with Liquid as I expected it solve my problems but there was so little info on the Net and it seemed to me like noone besides Shopify is using it.

    Regarding the variables, I’ll rephrase: what’s the automated way to get the list of variables that are available in the view? If I suddenly refactor my controller, how will my user get an updated list?

  • Gerhard

    I have tried Liquid many times and hated it every single one of them. ERB gets things done quickly and it’s very straightforward, can’t say the same about Liquid. You can have horribly written plain Ruby code (eg. fat models), ERB has nothing to do with “bad views”.

    Take a step back and look at your Liquid view snippets. Does that look good? Does that even look right? Wow!

    limit:3

    You do realize that views have nothing to do with the coupling that you’re referring to, that originates in the controllers. Views use what you give them, end of. Why expose models to views in the first place?

  • http://nicknotfound.com Nick

    I’ve been using Liquid in a large content management system, and almost every part of it is great for my needs. It allows my customers to edit their websites with dynamic content without security risks inherent to Ruby scripting.

    I’ve written hundreds of custom filters and dozens of custom blocks/tags. Liquid is fast and efficient in my experience, and it’s a great way of making dynamic content available to customers wherever they can edit a view.

    I wouldn’t use Liquid in place of ERB in cases where I (the developer) am writing the views, but for views that need to be editable by someone outside our company (e.g., our customers), Liquid is wonderful, especially since ERB isn’t really an option for this use case.

    @Jig: I’m not sure of a built-in way of getting all of the available variables, but you could write a custom tag for this.

    @Richard: There is a {% raw %} tag that will prevent Liquid from attempting to interpret your Handlebars templates. I do exactly this in some of my views.

    • http://blog.nhocki.com Nicolás Hock

      Could you please provide a small example of how you are rendering the templates? If you read the liquid source from a DB string, parse it and render it, it returns a string… how do you actually say ” render html: ‘the string’ “? Specially for things like editable CSS files (with Liquid).

  • Thomas

    As far as I can see, Liquid tries to build a code barrier by implementing an own language for things that could be better done with Ruby. The only good reason for this is to allow users of an app to edit the views. So the really interesting question is how secure Liquid is in such a use case.

    The price you have to pay is to learn another language for things you allready know how to do them. Filters e.g. look like method chaining. Second you are limited to the limits of this language. And I guess, there are performance penalties too.

    Seperation of concerns is not an argument against ERB. This argument reminds me to PHP Smarty, where this argument was one big reason to create the Smarty beast while in PHP templating always was dead easy because it was built-in into PHP just from the start.

    Separation of concerns is something you should be aware of as a developer. The framework should help you, but not by blocking you throug missing language features.

  • hao

    I don’t think there is anything wrong with ERB, and Liquid is not and will not be a replacement of ERB or HAML.
    Liquid is similar to dynamic template of PHP, use Liquid with ERB together in projects like CMS will be perfect.