Search code examples
ruby-on-rails-3.2mustacherabl

How to use rabl with mustache and ruby on rails


I am using ruby 1.9.3p125 and rails 3.2.8 and added rabl to my gemfile today, so it should be up to date.

I have used RABL in a simple situation where I wanted the json sent directly to the requester. Now I have a situation in which I want to use rabl to generate the json, then have it rendered by mustache.

Before this I have been been using as_json (overridden in the model) to generate the json, thus:

 <%= render 'scrollable', :mustache=>{photos: @page.photos.as_json} %>

where there's a suitable template in _scrollable.html.mustache, which I still wish to use.

I've written RABL templates for the photos thus:

# _photo.json.rabl
object @photo do
  attributes :src, :name, :height
  attributes :drawing

  node do |p|
    { :label => p.caption || p.name }
  end

  child :components do
    attributes :name, :height
  end

end

and

# _photos.json.rabl
collection @photos do
  extend 'photos/photo'
end

How do I get these templates called?

  <%= render 'scrollable', :mustache =>render(@page.photos, template: 'photos', formats: '[json]', handlers: ['rabl'])  %>

returns with

Missing partial ..../photos/photo with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee, :mustache, :rabl]}

which is interesting in that it seems to have lost the fact that I want formats: json


Solution

  • I'm doing something similar, but call the Rabl renderer directly and ask it for a hash rather than a json string, then use that as the mustache data...

    render 'posts.mustache', :mustache=>Rabl::Renderer.new('posts.rabl', @posts, :view_path => 'app/views', :format => 'hash').render
    

    I think mustache is expecting an object not a string.