[英]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。
首先,我們將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
希望這可以闡明一個示例,說明有人如何在Rails應用程序中使用stache
和mustache
提供正確的視圖模板。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.