1

我们正在使用Mustache模板,我想在我们的 RoR Web 应用程序中创建一个预览视图,该应用程序结合了一个模板和我们存储在数据库中的一些数据,但它没有像我预期的那样工作,并且在互联网上进行了一些搜索(包括所以!),我没有找到任何包含活动模型的示例。

如何将 ActiveModel 记录通过管道传输到 Mustache 以与模板合并?

设置:

架构

create_table "templates", :force => true do |t|
  t.string   "kind"
  t.text     "data"
  t.integer  "data_count"
end
create_table "bars", :force => true do |t|
  t.string   "guid"
  t.string   "name"
  t.string   "summary"
end

模型没有什么特别之处。两者都是 ActiveRecord::Base 的子类

class Bars < ActiveRecord::Base
end
class Templates < ActiveRecord::Base
end

控制器

class TemplateController < ApplicationController
  def preview
    @result = Mustache.render( template.data, :bars => Bar.limit(template.data_count ) ).html_safe
  end
end

风景

<%= @result %>

路线

get 'templates/:id/preview' => 'templates#preview', :as => 'templates_preview'

数据

y Bar.all

--- 
- !ruby/object:Bar
  attributes: 
    guid: "1"
    name: "test1"
- !ruby/object:Bar
  attributes: 
    guid: "2"
    name: "test2"

模板(出于示例目的,我已经简化了 html)

<html>
<head>
</head>
<body>
  {{#bars}}
    <a href="{{guid}}">{{name}}</a>
  {{/bars}}
</body>
</html>

结果

<html>
<head>
</head>
<body>
    <a href=""></a>
</body>
</html>

期望

<html>
<head>
</head>
<body>
    <a href="1">test1</a><a href="2">test2</a>
</body>
</html>

我希望有一个简单的答案,我只是想念它。谢谢。

4

1 回答 1

6

如果您将控制器更改为:

@result = Mustache.render( template.data, :bars => Bar.limit(template.data_count).all ).html_safe

(添加了对.allafter的调用Bar.limit(template.data_count)

我对 Mustache 很陌生,但是快速浏览代码似乎表明它为一个部分调用了这个:

v = [v] unless v.is_a?(Array) || defined?(Enumerator) && v.is_a?(Enumerator)

Bar.limit(template.data_count)返回 an ActiveRecord::Relation,它既不是 anArray也不是 an Enumerator。调用.all关系会将其转换为一个数组,并导致 Mustache 将其相应地传递到该部分。

于 2011-03-12T17:20:59.060 回答