Skip to content

Instantly share code, notes, and snippets.

@holamendi
Last active March 17, 2016 14:18
Show Gist options
  • Save holamendi/603d7d36c6e252304591 to your computer and use it in GitHub Desktop.
Save holamendi/603d7d36c6e252304591 to your computer and use it in GitHub Desktop.
Ejemplo Liquid
# los drops son para definir que se puede exponer en un template
class ProductDrop < Liquid::Drop
def initialize(product)
@product = product
end
def name
@product[:name]
end
def price
@product[:name]
end
end
# los filters nos permiten definir "helpers" para los templates
class PriceFilter
def to_price(input)
"$ #{input}"
end
end
# le decimos a liquid que vamos a usar este filter
Liquid::Template.register_filter(PriceFilter)
template_string = %(
{% for product in products %}
<p>{{product.name}} - {{product.price | to_price}}</p>
{% end %}
)
# un array de hash para este ejemplo, pero en spincommerce usamos models
products = [
{ name: 'Skate', price: 5000},
{ name: 'Wheels', price: 2000}
]
# acá ocurre toda la magia
liquid_template = Liquid::Template.parse(template_string)
# seteamos los objectus que se usan en el contexto del template
liquid_template.assigns['products'] = products.map{ |product| ProductDrop.new(product) }
# hacemos el render, que nos devuelve un string con el html parseado
liquid_template.render
# nos devuelve esto
#
# <p>Skate - $ 5000</p>
# <p>Wheels - $ 2000</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment