5

我可以做:

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

在我的控制器中,但将 view_template_in_a_string 放在 view/controllername/action.mustache.html 下的 viewname.mustache.html 文件中似乎更传统,就像我使用 action.html.erb 一样

目前我使用

gem 'mustache'

满足我的小胡子需求

如何像使用 erb 一样使用小胡子视图


我知道小胡子是没有逻辑的,我的观点不需要逻辑


我目前的黑客:

# 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
4

2 回答 2

4

自原始解决方案 mustache-rails 不复存在以来的更新答案。

宝石是:

https://github.com/agoragames/stache

还有一个多余但简单的示例来说明如何在我们的 rails 项目中使用 stache,我们将开始一个 Noises 演示应用程序。

首先,我们将把 themustachestachegem 添加到我们的 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

希望这能阐明一个示例,说明人们如何使用stachemustache在 Rails 应用程序中提供正确的视图模板。

于 2015-08-13T19:07:24.067 回答
1

只需使用这个宝石:

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

这样您就可以轻松配置 Rails 应用程序以提供正确的视图模板,这样您就不再需要 hack。

于 2013-04-02T08:44:23.727 回答