Ditching ERB: A Guide to Using Liquid

Share this article

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}} [gist id=’3202509′]

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. [gist id=’3202511′] 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. [gist id=’3202513′]

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. [gist id=’3202515′] 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: [gist id=’3118892′] 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: https://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: [gist id=’3118852′] 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: [gist id=’3220855′] 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.

Frequently Asked Questions (FAQs) about Using Liquid in Rails

What are the benefits of using Liquid over ERB in Rails?

Liquid is a powerful and safe templating engine used by many platforms, including Shopify. It offers several advantages over ERB. Firstly, it provides a secure environment where users can edit the application’s templates without affecting the server-side code. This is particularly useful in multi-tenant applications where each user needs to customize their interface. Secondly, Liquid has a simple and intuitive syntax that is easy to learn and use. It also supports advanced features like filters and tags, which can simplify complex operations.

How do I install and set up Liquid in a Rails application?

Installing Liquid in a Rails application is straightforward. You need to add the ‘liquid’ gem to your Gemfile and run the ‘bundle install’ command. After that, you can use Liquid templates in your views by changing the file extension from ‘.html.erb’ to ‘.liquid’. You can also use the ‘render’ method in your controllers to render Liquid templates.

Can I use Liquid filters in Rails, and how do they work?

Yes, you can use Liquid filters in Rails. Filters are simple methods that modify the output of numbers, strings, variables, and objects. They are placed within an output tag and are denoted by a pipe character ‘|’. For example, the ‘upcase’ filter can be used to convert a string to uppercase.

How can I create custom Liquid tags in Rails?

Creating custom Liquid tags in Rails involves defining a new class that inherits from ‘Liquid::Tag’ and implementing the ‘render’ method. This method takes a context object and returns a string that will replace the tag in the template. Once the tag class is defined, you can register it with Liquid using the ‘Liquid::Template.register_tag’ method.

How do I handle errors and exceptions in Liquid?

Liquid has a robust error handling mechanism. It catches and suppresses all exceptions by default, and replaces them with a blank string in the output. However, you can customize this behavior by setting the ‘error_mode’ option on the Liquid::Template object. You can also use the ‘errors’ method to retrieve a list of errors that occurred during rendering.

Can I use Liquid in combination with other templating engines like Haml or Slim?

Yes, you can use Liquid in combination with other templating engines like Haml or Slim. However, you need to be aware of the differences in syntax and behavior between these engines. For example, Haml uses indentation to denote nesting, while Liquid uses tags.

How do I test Liquid templates in Rails?

Testing Liquid templates in Rails can be done using the standard Rails testing tools. You can create a test that renders the template with a set of inputs and asserts that the output matches the expected result. You can also use libraries like Capybara to perform integration tests that involve Liquid templates.

How do I debug Liquid templates in Rails?

Debugging Liquid templates in Rails can be challenging due to the lack of traditional debugging tools like ‘binding.pry’. However, you can use the ‘inspect’ filter to output the value of a variable in the template. You can also use the ‘errors’ method to retrieve a list of errors that occurred during rendering.

Can I use Liquid to generate dynamic content in Rails?

Yes, you can use Liquid to generate dynamic content in Rails. You can pass variables from your controllers to your Liquid templates, and use these variables in combination with Liquid tags and filters to generate dynamic content.

How do I secure Liquid templates in Rails?

Securing Liquid templates in Rails involves restricting the types of operations that can be performed in the template. By default, Liquid disallows operations that could affect the server-side code or the underlying system. However, you can further restrict the available tags and filters by using a custom ‘Liquid::Context’ object.

Daniel CooperDaniel Cooper
View Author

Daniel Cooper is a web developer from Brighton, UK

Share this article
Read Next
From Idea to Prototype in Minutes: Claude Sonnet 3.5
From Idea to Prototype in Minutes: Claude Sonnet 3.5
Zain
Essential Plugins for WordPress Developers: Top Picks for 2024
Essential Plugins for WordPress Developers: Top Picks for 2024
SitePoint Sponsors
WebAssembly vs JavaScript: A Comparison
WebAssembly vs JavaScript: A Comparison
Kaan Güner
The Functional Depth of Docker and Docker Compose
The Functional Depth of Docker and Docker Compose
Vultr
How Top HR Agencies Build Trust Through Logo Designs
How Top HR Agencies Build Trust Through Logo Designs
Evan Brown
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
SitePoint Sponsors
10 Artificial Intelligence APIs for Developers
10 Artificial Intelligence APIs for Developers
SitePoint Sponsors
The Ultimate Guide to Navigating SQL Server With SQLCMD
The Ultimate Guide to Navigating SQL Server With SQLCMD
Nisarg Upadhyay
Retrieval-augmented Generation: Revolution or Overpromise?
Retrieval-augmented Generation: Revolution or Overpromise?
Kateryna ReshetiloOlexandr Moklyak
How to Deploy Apache Airflow on Vultr Using Anaconda
How to Deploy Apache Airflow on Vultr Using Anaconda
Vultr
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Dave NearyAaron Williams
How to Create Content in WordPress with AI
How to Create Content in WordPress with AI
Çağdaş Dağ
A Beginner’s Guide to Setting Up a Project in Laravel
A Beginner’s Guide to Setting Up a Project in Laravel
Claudio Ribeiro
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Gitlab
Creating Fluid Typography with the CSS clamp() Function
Creating Fluid Typography with the CSS clamp() Function
Daine Mawer
Comparing Full Stack and Headless CMS Platforms
Comparing Full Stack and Headless CMS Platforms
Vultr
7 Easy Ways to Make a Magento 2 Website Faster
7 Easy Ways to Make a Magento 2 Website Faster
Konstantin Gerasimov
Powerful React Form Builders to Consider in 2024
Powerful React Form Builders to Consider in 2024
Femi Akinyemi
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Ralph Mason
Sending Email Using Node.js
Sending Email Using Node.js
Craig Buckler
Creating a Navbar in React
Creating a Navbar in React
Vidura Senevirathne
A Complete Guide to CSS Logical Properties, with Cheat Sheet
A Complete Guide to CSS Logical Properties, with Cheat Sheet
Ralph Mason
Using JSON Web Tokens with Node.js
Using JSON Web Tokens with Node.js
Lakindu Hewawasam
How to Build a Simple Web Server with Node.js
How to Build a Simple Web Server with Node.js
Chameera Dulanga
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Beloslava Petrova
Crafting Interactive Scatter Plots with Plotly
Crafting Interactive Scatter Plots with Plotly
Binara Prabhanga
GenAI: How to Reduce Cost with Prompt Compression Techniques
GenAI: How to Reduce Cost with Prompt Compression Techniques
Suvoraj Biswas
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
Aurelio De RosaMaria Antonietta Perna
Quick Tip: How to Align Column Rows with CSS Subgrid
Quick Tip: How to Align Column Rows with CSS Subgrid
Ralph Mason
15 Top Web Design Tools & Resources To Try in 2024
15 Top Web Design Tools & Resources To Try in 2024
SitePoint Sponsors
7 Simple Rules for Better Data Visualization
7 Simple Rules for Better Data Visualization
Mariia Merkulova
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
SitePoint Team
Best Programming Language for AI
Best Programming Language for AI
Lucero del Alba
Quick Tip: How to Add Gradient Effects and Patterns to Text
Quick Tip: How to Add Gradient Effects and Patterns to Text
Ralph Mason
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Vultr
How to Optimize Website Content for Featured Snippets
How to Optimize Website Content for Featured Snippets
Dipen Visavadiya
Psychology and UX: Decoding the Science Behind User Clicks
Psychology and UX: Decoding the Science Behind User Clicks
Tanya Kumari
Build a Full-stack App with Node.js and htmx
Build a Full-stack App with Node.js and htmx
James Hibbard
Digital Transformation with AI: The Benefits and Challenges
Digital Transformation with AI: The Benefits and Challenges
Priyanka Prajapat
Quick Tip: Creating a Date Picker in React
Quick Tip: Creating a Date Picker in React
Dianne Pena
How to Create Interactive Animations Using React Spring
How to Create Interactive Animations Using React Spring
Yemi Ojedapo
10 Reasons to Love Google Docs
10 Reasons to Love Google Docs
Joshua KrausZain Zaidi
How to Use Magento 2 for International Ecommerce Success
How to Use Magento 2 for International Ecommerce Success
Mitul Patel
5 Exciting New JavaScript Features in 2024
5 Exciting New JavaScript Features in 2024
Olivia GibsonDarren Jones
Tools and Strategies for Efficient Web Project Management
Tools and Strategies for Efficient Web Project Management
Juliet Ofoegbu
Choosing the Best WordPress CRM Plugin for Your Business
Choosing the Best WordPress CRM Plugin for Your Business
Neve Wilkinson
ChatGPT Plugins for Marketing Success
ChatGPT Plugins for Marketing Success
Neil Jordan
Managing Static Files in Django: A Comprehensive Guide
Managing Static Files in Django: A Comprehensive Guide
Kabaki Antony
The Ultimate Guide to Choosing the Best React Website Builder
The Ultimate Guide to Choosing the Best React Website Builder
Dianne Pena
Exploring the Creative Power of CSS Filters and Blending
Exploring the Creative Power of CSS Filters and Blending
Joan Ayebola
How to Use WebSockets in Node.js to Create Real-time Apps
How to Use WebSockets in Node.js to Create Real-time Apps
Craig Buckler
Best Node.js Framework Choices for Modern App Development
Best Node.js Framework Choices for Modern App Development
Dianne Pena
SaaS Boilerplates: What They Are, And 10 of the Best
SaaS Boilerplates: What They Are, And 10 of the Best
Zain Zaidi
Understanding Cookies and Sessions in React
Understanding Cookies and Sessions in React
Blessing Ene Anyebe
Enhanced Internationalization (i18n) in Next.js 14
Enhanced Internationalization (i18n) in Next.js 14
Emmanuel Onyeyaforo
Essential React Native Performance Tips and Tricks
Essential React Native Performance Tips and Tricks
Shaik Mukthahar
How to Use Server-sent Events in Node.js
How to Use Server-sent Events in Node.js
Craig Buckler
Five Simple Ways to Boost a WooCommerce Site’s Performance
Five Simple Ways to Boost a WooCommerce Site’s Performance
Palash Ghosh
Elevate Your Online Store with Top WooCommerce Plugins
Elevate Your Online Store with Top WooCommerce Plugins
Dianne Pena
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Dianne Pena
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
Vultr
Enhance Your React Apps with ShadCn Utilities and Components
Enhance Your React Apps with ShadCn Utilities and Components
David Jaja
10 Best Create React App Alternatives for Different Use Cases
10 Best Create React App Alternatives for Different Use Cases
Zain Zaidi
Control Lazy Load, Infinite Scroll and Animations in React
Control Lazy Load, Infinite Scroll and Animations in React
Blessing Ene Anyebe
Building a Research Assistant Tool with AI and JavaScript
Building a Research Assistant Tool with AI and JavaScript
Mahmud Adeleye
Understanding React useEffect
Understanding React useEffect
Dianne Pena
Web Design Trends to Watch in 2024
Web Design Trends to Watch in 2024
Juliet Ofoegbu
Building a 3D Card Flip Animation with CSS Houdini
Building a 3D Card Flip Animation with CSS Houdini
Fred Zugs
How to Use ChatGPT in an Unavailable Country
How to Use ChatGPT in an Unavailable Country
Dianne Pena
An Introduction to Node.js Multithreading
An Introduction to Node.js Multithreading
Craig Buckler
How to Boost WordPress Security and Protect Your SEO Ranking
How to Boost WordPress Security and Protect Your SEO Ranking
Jaya Iyer
Understanding How ChatGPT Maintains Context
Understanding How ChatGPT Maintains Context
Dianne Pena
Building Interactive Data Visualizations with D3.js and React
Building Interactive Data Visualizations with D3.js and React
Oluwabusayo Jacobs
JavaScript vs Python: Which One Should You Learn First?
JavaScript vs Python: Which One Should You Learn First?
Olivia GibsonDarren Jones
13 Best Books, Courses and Communities for Learning React
13 Best Books, Courses and Communities for Learning React
Zain Zaidi
5 jQuery.each() Function Examples
5 jQuery.each() Function Examples
Florian RapplJames Hibbard
Implementing User Authentication in React Apps with Appwrite
Implementing User Authentication in React Apps with Appwrite
Yemi Ojedapo
AI-Powered Search Engine With Milvus Vector Database on Vultr
AI-Powered Search Engine With Milvus Vector Database on Vultr
Vultr
Understanding Signals in Django
Understanding Signals in Django
Kabaki Antony
Why React Icons May Be the Only Icon Library You Need
Why React Icons May Be the Only Icon Library You Need
Zain Zaidi
View Transitions in Astro
View Transitions in Astro
Tamas Piros
Getting Started with Content Collections in Astro
Getting Started with Content Collections in Astro
Tamas Piros
What Does the Java Virtual Machine Do All Day?
What Does the Java Virtual Machine Do All Day?
Peter Kessler
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Mayank Singh
Layouts in Astro
Layouts in Astro
Tamas Piros
.NET 8: Blazor Render Modes Explained
.NET 8: Blazor Render Modes Explained
Peter De Tender
Mastering Node CSV
Mastering Node CSV
Dianne Pena
A Beginner’s Guide to SvelteKit
A Beginner’s Guide to SvelteKit
Erik KückelheimSimon Holthausen
Brighten Up Your Astro Site with KwesForms and Rive
Brighten Up Your Astro Site with KwesForms and Rive
Paul Scanlon
Which Programming Language Should I Learn First in 2024?
Which Programming Language Should I Learn First in 2024?
Joel Falconer
Managing PHP Versions with Laravel Herd
Managing PHP Versions with Laravel Herd
Dianne Pena
Accelerating the Cloud: The Final Steps
Accelerating the Cloud: The Final Steps
Dave Neary
An Alphebetized List of MIME Types
An Alphebetized List of MIME Types
Dianne Pena
The Best PHP Frameworks for 2024
The Best PHP Frameworks for 2024
Claudio Ribeiro
11 Best WordPress Themes for Developers & Designers in 2024
11 Best WordPress Themes for Developers & Designers in 2024
SitePoint Sponsors
Top 10 Best WordPress AI Plugins of 2024
Top 10 Best WordPress AI Plugins of 2024
Dianne Pena
20+ Tools for Node.js Development in 2024
20+ Tools for Node.js Development in 2024
Dianne Pena
The Best Figma Plugins to Enhance Your Design Workflow in 2024
The Best Figma Plugins to Enhance Your Design Workflow in 2024
Dianne Pena
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Christopher Collins
Build Your Own AI Tools in Python Using the OpenAI API
Build Your Own AI Tools in Python Using the OpenAI API
Zain Zaidi
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form