在Rails中使用mustache视图模板的最简单方法是什么?

5

我可以做到:

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

在我的控制器中,但似乎更传统的做法是将view_template_in_a_string放在自己的viewname.mustache.html文件中,该文件位于views/controllername/action.mustache.html下,就像我使用action.html.erb一样。

目前我使用:

gem 'mustache'

为了满足我的胡子需求

我该怎样像使用erb一样使用mustache视图?


我知道mustache是没有逻辑的,我不需要在视图中使用逻辑。


我当前的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
2个回答

4

自从原始解决方案mustache-rails停止更新后,现在提供一个更新的答案。

该gem是:

https://github.com/agoragames/stache

下面是一个简单但有用的例子,展示如何在rails项目中使用stache,我们将创建一个Noises Demo App。

首先,在Gemfile中添加mustachestache gem,并运行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

希望这个例子能够说明如何在Rails应用中使用stachemustache来提供正确的视图模板。

1

4
这颗宝石已经不存在了。由于唯一的答案是您的,我建议您进行更新。 - installero

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接