-
Notifications
You must be signed in to change notification settings - Fork 1.5k
ES Liquid para programadores
Es muy fácil empezar con Liquid.
Un template Liquid se renderiza en dos pasos: Parseo y renderización.
Para una introducción a la sintáxis de Liquid, por favor lee: ES-Liquid para Diseñadores.
@template = Liquid::Template.parse("hi {{name}}") # Parsea y compila el template
@template.render( 'name' => 'tobi' ) # Renderiza el texto => "hi tobi"
El paso de parseo crea un template totalmente compilado que puede ser re-usado tantas veces como uno quiera.
Se puede guardar en memoria o en una caché para renderizar con velocidad más adelante.
Todos los parámetros que quieras utilizar en el template Liquid deberán ser pasados como parámetros en el método render.
Liquid no sabe de tus variables locales, de instancia o globales.
Es muy fácil extender Liquid.
Sin embargo, ten en cuenta que Liquid es una librería joven que requiere ayuda de todos.
Si creas filtros y tags útiles, por favor considera crear un patch y mandarlo como un issue aquí.
Es muy fácil crear filtros.
Básicamente, son métodos que toman solo un parámtro y devuelven un string modificado.
Puedes usar tus propios filtros, pasando un array de módulos así:
@template.render(assigns, [MyTextFilters, MyDateFilters]).
module TextFilter
def textilize(input)
RedCloth.new(input).to_html
end
end
@template = Liquid::Template.parse(" {{ '*hi*' | textilize }} ")
@template.render({}, :filters => [TextFilter]) # => "<b>hi</b>"
Alternativamente, también puedes registrar tus filtros globalmente:
module TextFilter
def textilize(input)
RedCloth.new(input).to_html
end
end
Liquid::Template.register_filter(TextFilter)
Una vez que el filtro está registrado globalmente, uno puede simplemente usarlo así:
@template = Liquid::Template.parse(" {{ '*hi*' | textilize }} ")
@template.render # => "<b>hi</b>"
Para crear un nuevo tag, simplemente debes heredar de Liquid::Tag y registrar tu block en Liquid::Template.
class Random < 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', Random)
@template = Liquid::Template.parse(" {% random 5 %}")
@template.render # => "3"
Todos los block tags son parseados por Liquid.
Para crear un nuevo bloque, solo debes heredar de Liquid::Block y registrar tu bloque en Liquid::Template.
class Random < Liquid::Block
def initialize(tag_name, markup, tokens)
super
@rand = markup.to_i
end
def render(context)
if rand(@rand) == 0
super
else
''
end
end
end
Liquid::Template.register_tag('random', Random)
text = " {% random 5 %} wanna hear a joke? {% endrandom %} "
@template = Liquid::Template.parse(text)
@template.render # => In 20% of the cases, this will output "wanna hear a joke?"