2014年6月8日 星期日

mustache

Mustache is a wonderfully simple templating language that is supported by a number of programming languages, including Ruby and JavaScript

/app/views/products/index.html.erb
<div id="products" data-json-url="<%= products_url(:format => :json) %>">
getJSON to get the products JSON from that URL. The getJSON function takes a callback function that fires when the data is returned and we’ll pass in a new function called render
/app/assets/products.js.coffee
 $.getJSON($('#products').data('json-url'), @render)
As our partial is a Mustache template it will need to have a .mustache extension rather than the usual .erb.
/config/initalizers/mustache_template_handler.rb
module MustacheTemplateHandler
  def self.call(template)
    if template.locals.include? :mustache
      "Mustache.render(#{template.source.inspect}, mustache).html_safe"
    else
      "#{template.source.inspect}.html_safe" 
     end
  end
end


ActionView::Template.register_template_handler(:mustache, MustacheTemplateHandler)
template.source which is the content of the template that’s being rendered
inspect on this to return an object which will be the string-escaped version of it’s Ruby representation
html_safe on the output from this to make sure that it’s escaped properly
render the template out using the Ruby Mustache passing in the mustache variable that contains the current product.Otherwise we render out the raw template for JavaScript to deal with on the client
register the new handler by calling register_template_handler, passing in the name of the handler and our module.
render json: @products.map { |p| view_context.products_for_mustache(p) }
Note that as we’re calling a helper method from a controller we need to call it through view_context.


沒有留言:

張貼留言