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

时间:2013-04-02 00:31:35

标签: ruby-on-rails gem mustache

我能做到:

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

2 个答案:

答案 0 :(得分:4)

自原始解决方案以来,更新的答案仍然存在。

宝石是:

https://github.com/agoragames/stache

这是一个冗余但简单的例子,用于解决如何在我们的rails项目中使用stache,我们将开始使用Noises演示应用程序。

首先,我们将 public void Run() { for (int i = 0; i < 10; i++) { Thread t = new Thread(() => myFun((i + 1))); t.Start(); } } private void myFun(int threadNo) { Console.WriteLine("Thread #" + threadNo.ToString()); } mustache gem添加到我们的Gemfile中并运行stache

然后在我们的bundle install中,我们需要告诉config/application.rb使用stache(其他可用选项为mustache;此外,还可以找到此选项和其他配置选项他们的github page)。

handlebars

这是示例目录结构,其中包含一些应用程序的示例文件:

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

希望这清楚地说明了某人如何在rails应用程序中使用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来提供正确的视图模板。

答案 1 :(得分:1)

只需使用这个宝石:

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

通过这种方式,您可以轻松配置rails应用程序以提供正确的视图模板,从而不再需要您的黑客攻击。

相关问题