Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the simplest way to use mustache view templates in rails?

I could do:

render :text => Mustache.render(view_template_in_a_string, object_hash)

in my controller, but it seems more conventional to put view_template_in_a_string in it's own viewname.mustache.html file under views/controllername/action.mustache.html like I would with action.html.erb

currently I use

gem 'mustache'

for my mustache needs

How can I use mustache views like I would with erb


I understand that mustache is logic-less, I don't need logic in my views


my current hack:

# controllers/thing_controller.rb
def some_action
    hash = {:name => 'a name!!'}
    vw = File.read('./app/views/'+params[:controller]+'/'+params[:action]+'.html.mustache') || ""
    render :text => Mustache.render(vw, hash), :layout => true
end
like image 293
Hayk Saakian Avatar asked Apr 02 '13 00:04

Hayk Saakian


2 Answers

An updated answer since the original solution, mustache-rails, ceases to exist.

The gem is:

https://github.com/agoragames/stache

And a redundant but simple example to address how to use stache in our rails project, we'll make the beginning of a Noises Demo App.

To start we'll add both the mustache and the stache gem into our Gemfile and run bundle install.

Then in our config/application.rb we need to tell stache to use mustache (the other available option is handlebars; also, this and other configuration options can be found on their github page).

Stache.configure do |config|
  config.use :mustache
end

Here's the sample directory structure with a few example files for our app:

app/
  controllers/
    noises_controller.rb
    models/
      noise.rb
  templates/ 
    noises/
      animal.mustache
  views/ 
    noises/
      animal.rb 

In controllers/noises_controller.rb

class NoisesController < ApplicationController
  def animal
  end
end

In models/noise.rb

class Noise < ActiveRecord::Base 
  def self.dog 
    "ar roof"
  end

  def self.sheep 
    "baa"
  end 

  def self.bullfrog 
    "borborygmus"
  end 
end

In templates/noises/animal.mustache

<p>This is what a dog sounds like: {{ dog }}</p>
<p>This is what a sheep sounds like: {{ sheep }}</p>
<p>And bullfrogs can sound like: {{ bullfrog }}</p>

In views/noises/animal.rb

module Noises 
  class Animal < Stache::Mustache::View 
    def dog 
      Noise.dog
    end 

    def sheep 
      Noise.sheep 
    end 

    def bullfrog 
      Noise.bullfrog 
    end 
  end
end

Hopefully this clarifies an example of how someone can use stache and mustache in a rails application to serve the correct view templates.

like image 197
elizabae Avatar answered Sep 20 '22 08:09

elizabae


Just use this gem:

https://github.com/josh/mustache-rails

That way you can easily configure your rails application to serve the correct view templates, so that you no longer need your hack.

like image 38
Arjan Avatar answered Sep 21 '22 08:09

Arjan