-
Notifications
You must be signed in to change notification settings - Fork 11
Getting Liquid to Work in Rails
Liquid comes with a proper init.rb
file, by default.
To start using Liquid, just extract it into vendor/plugins
.
Better yet, use the ./script/plugin
script to install Liquid.
You can now start using templates with the .liquid
file type (ie, extension).
A note about helpers.
Liquid’s Rails plugin tries to use your helpers as Filters.
Your helpers will always receive the piped-in text as the first parameter,
and then any Filter parameters (passed after the colon).
Helper:
module ApplicationHelper
def truncate(input, length)
input[0..length] + ‘…’
end
end
Liquid:
{{ ‘This is a long section of text’ | truncate: 3 }} #=> Thi…
Insert
{{ content_for_layout }}
in your liquid layout where you would put
<%= yield %>
in an erb layout.
Note: if you are collecting content with <% content_for :foo do %> ... <% end %>
then there is currently no way to access this in a liquid layout.
When you pass variables to be available in a Liquid template,
Liquid accepts a limited number of object types —
Strings, Arrays, Hashes, Numerics, and Booleans.
If you’d like to pass your ActiveRecord (or other) objects to a Liquid template,
you have three basic approaches:
The easy way is to add a liquid_methods
call:
class Post < ActiveRecord::Base liquid_methods :title, :body, :comments ...
Behind the scenes,
liquid_methods
actually constructs a
Liquid Drop with the methods you include.
This way, you have lazy loading
(say, of associated models such as “comments” in the example above) of methods.
An alternate route is to add a to_liquid
call in your object,
returning either one of the types listed above (string, array, hash, etc)
or an object that in turn responds to to_liquid
.
class Post < ActiveRecord::Base ... def to_liquid {'title' => title, 'body' => body} end
Finally, you can write and register a completely new
Liquid Drop class.
This enables you to pull from various models
and helps you consolidate (lazy-loaded) methods used just for passing data to templates.