Skip to content

Instantly share code, notes, and snippets.

@fddayan
Created June 4, 2014 16:47
Show Gist options
  • Save fddayan/f958ecfe47f8c23d97ae to your computer and use it in GitHub Desktop.
Save fddayan/f958ecfe47f8c23d97ae to your computer and use it in GitHub Desktop.
Different ways of extending liquid
source "https://rubygems.org"
gem 'liquid'
gem 'RedCloth'
require 'liquid'
require 'RedCloth'
# SIMPLE
@template = Liquid::Template.parse("hi {{name}}") # Parses and compiles the template
puts @template.render( 'name' => 'tobi' )
# REGISTER FILTER
module TextFilter
def textilize(input)
RedCloth.new(input).to_html
end
end
Liquid::Template.register_filter(TextFilter)
@template = Liquid::Template.parse(" {{ '*hi*' | textilize }} ")
puts @template.render # => "<b>hi</b>"
# CUSTOM TAG
class Randomnum < Liquid::Tag
def initialize(tag_name, max, tokens)
super
@max = max.to_i
end
def render(context)
rand(@max).to_s
end
end
Liquid::Template.register_tag('random', Randomnum)
@template = Liquid::Template.parse(" {% random 5 %}")
puts @template.render # => "3"
# CUSTOM BLOCK
class Randomblock < Liquid::Block
def initialize(tag_name, markup, tokens)
super
@rand = markup.to_i
end
def render(context)
if rand(@rand) == 0
super
else
'nope'
end
end
end
Liquid::Template.register_tag('randomblock', Randomblock)
text = " {% randomblock 2 %} wanna hear a joke? {% endrandomblock %} "
@template = Liquid::Template.parse(text)
puts @template.render # => In 20% of the cases, this will output "wanna hear a joke?"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment