我们正在使用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>
我希望有一个简单的答案,我只是想念它。谢谢。