What is the easiest way to use mustache viewing patterns in rails?

I could do:

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

in my controller, but it seems more common to put view_template_in_a_string in your own viewname.mustache.html file under view / controllername / action.mustache.html, as I would do with action.html.erb

I am currently using

gem 'mustache'

for my mustache needs

How can I use mustache representations, for example with erb


I understand that the mustache does not have logic, I do not need logic in my representations


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
+5
source share
2 answers

Just use this stone:

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

, - , .

+1

, , -, .

:

https://github.com/agoragames/stache

, , stache rails, Demo Demo App.

, mustache, stache Gemfile bundle install.

config/application.rb stache mustache ( handlebars; github).

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

:

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

controllers/noises_controller.rb

class NoisesController < ApplicationController
  def animal
  end
end

models/noise.rb

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

  def self.sheep 
    "baa"
  end 

  def self.bullfrog 
    "borborygmus"
  end 
end

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>

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

, , - stache mustache rails .

+4

All Articles