繁体   English   中英

在rails中使用小胡子视图模板的最简单方法是什么?

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

我可以做:

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一样使用小胡子视图


我知道小胡子没逻辑,我不需要逻辑


我目前的骇客:

# 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

由于原始解决方案“胡须栏杆”不复存在,因此有了更新的答案。

宝石是:

https://github.com/agoragames/stache

还有一个多余但简单的示例来解决如何在Rails项目中使用stache,我们将开始创建Noises Demo App。

首先,我们将mustachestache宝石都添加到我们的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

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

只需使用以下宝石:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM