5

私はそれをできた:

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

私のコントローラーでは、しかし、action.html.erb の場合のように、view_template_in_a_string を views/controllername/action.mustache.html の下にある独自の viewname.mustache.html ファイルに配置する方が従来のようです。

現在私が使用している

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

元のソリューションである口ひげレールが存在しなくなったため、更新された回答。

宝石は次のとおりです。

https://github.com/agoragames/stache

Rails プロジェクトで stache を使用する方法を説明するための冗長ではあるが単純な例として、Noises Demo App の冒頭を作成します。

まず、mustachestachegem の両方を Gemfile に追加して、 を実行しますbundle install

次に、使用するconfig/application.rbように指示する必要があります (他の使用可能なオプションはです。また、これと他の構成オプションはgithub ページにあります)。stachemustachehandlebars

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

stacheこれにより、Rails アプリケーションでとを使用mustacheして正しいビュー テンプレートを提供する方法の例が明確になることを願っています。

于 2015-08-13T19:07:24.067 に答える