December 05, 2009
Rendering Liquid templates from outside the views directory
Today I’m working with Liquid in Rails. I’m setting up a theme system for this project so I decided to store the liquid templates in RAILS_ROOT/app/themes. With all of that said, lets start from the beginning.
First add the Liquid gem to the environements.rb file.
1 2 |
# RAILS_ROOT/config/environments.rb config.gem "tobi-liquid", :lib => "liquid", :version => ">= 2.0.1", :source => "https://gems.github.com" |
Next unpack the gem with: rake gems:unpack. That will add the gem to vendor/gems. At this point you can render liquid templates within the app/views directory, but not outside of the views. You can test this by creating some controller and replacing the view’s .html.erb extension with .liquid and tell the controller to render the liquid template: render "your_file.liquid"
I’d like to render liquid templates that exist in app/themes so I did the following: render "#{RAILS_ROOT}/app/themes/default/templates/index.liquid"
Instead of rendering the template like I expected, my browser downloaded the unprocessed liquid file. This is all handled with ActionView. I don’t know why ActionView will only render liquid templates within the app/views directory, but it will render regular .erb files from anywhere.
The solution was very simple after looking over the Liquid’s LiquidView documentation. I just had to tell ActionView to handle liquid files with LiquidView! This documentation is just old enough to not work anymore. ActionView::Base::register_template_handler was available at that location until version 2.1. It is now ActionView::Template.register_template_handler.
Finally make a liquid.rb file in config/initializers, require the extras/liquid_view path and register LiquidView to handle liquid templates. It should look like this:
1 2 3 4 |
# RAILS_ROOT/config/initializers/liquid.rb require 'extras/liquid_view' ActionView::Template.register_template_handler :liquid, LiquidView |
Ta-da! Now you can render liquid templates from any location!

Leave a Comment