Skip to content

Using Liquid without Rails

cannikin edited this page Aug 12, 2010 · 13 revisions

Want to use Liquid along with some plain old Ruby code? The secret is creating a to_liquid method on any classes you create.

Let’s say you have a Product class:

class Product
  attr_accessor :name, :price
  def initialize(name,price)
    @name = name
    @price = price
  end
end

And you have a chunk of text that you want to Liquidize by inserting some details about your products:

sentence = "I'm running to the store with {{ product.price }} dollars in my pocket to buy a {{ product.name }}."

And you create a product and parse the sentence:

my_purchase = Product.new('box of sausages', 20)
puts Liquid::Template.parse(sentence).render('product' => my_purchase)

You excitedly execute your code expecting to see your beautiful new sentence, but instead you get:

I'm running to the store with Liquid error: undefined method `to_liquid' for #<Product:0x1388c08 @title="box of sausages", @price=20> dollars in my pocket to buy a Liquid error: undefined method `to_liquid' for #<Product:0x1388c08 @title="box of sausages", @price=20>.

to_liquid? Where did that come from? Turns out you need to add a method to your class that returns your instance variables as part of a hash. (Liquid was built to be very paranoid about not letting people access something they’re not supposed to, so you need to explicitly let liquid know how to access everything in your object.) So we update the Product class description to include that method:

class Product
  attr_accessor :name, :price
  def initialize(name,price)
    @name = name
    @price = price
  end
  to_liquid
    { :name => self.name,
      :prict => self.price }
  end
end

Run that again and presto:

I'm running to the store with 20 dollars in my pocket to buy a box of sausages.

(Thanks to Tom’s Jekyll code for helping me figuring this out.)

Clone this wiki locally