sor*_*ens 1 ruby templates activemodel mustache ruby-on-rails-3
我们正在使用Mustache模板,我想在我们的RoR Web应用程序中创建一个预览View,它将模板和我们存储在数据库中的一些数据结合起来,但它不能像我预期的那样工作,并且在对互联网进行一些搜索之后(包括所以!),我没有找到包含活动模型的任何示例.
如何将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
Run Code Online (Sandbox Code Playgroud)
这些模型没有什么特别之处.两者都是ActiveRecord :: Base的子类
class Bars < ActiveRecord::Base
end
class Templates < ActiveRecord::Base
end
Run Code Online (Sandbox Code Playgroud)
控制器
class TemplateController < ApplicationController
def preview
@result = Mustache.render( template.data, :bars => Bar.limit(template.data_count ) ).html_safe
end
end
Run Code Online (Sandbox Code Playgroud)
风景
<%= @result %>
Run Code Online (Sandbox Code Playgroud)
路线
get 'templates/:id/preview' => 'templates#preview', :as => 'templates_preview'
Run Code Online (Sandbox Code Playgroud)
数据
y Bar.all
---
- !ruby/object:Bar
attributes:
guid: "1"
name: "test1"
- !ruby/object:Bar
attributes:
guid: "2"
name: "test2"
Run Code Online (Sandbox Code Playgroud)
模板(我为了示例目的简化了html)
<html>
<head>
</head>
<body>
{{#bars}}
<a href="{{guid}}">{{name}}</a>
{{/bars}}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
结果
<html>
<head>
</head>
<body>
<a href=""></a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
期望
<html>
<head>
</head>
<body>
<a href="1">test1</a><a href="2">test2</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我希望有一个简单的答案,我只是错过了它.谢谢.
如果将控制器更改为:
@result = Mustache.render( template.data, :bars => Bar.limit(template.data_count).all ).html_safe
Run Code Online (Sandbox Code Playgroud)
(添加了一个呼叫到.all后Bar.limit(template.data_count))
我是很新,小胡子,但一眼很快通过代码似乎表明,它调用此一节:
v = [v] unless v.is_a?(Array) || defined?(Enumerator) && v.is_a?(Enumerator)
Run Code Online (Sandbox Code Playgroud)
Bar.limit(template.data_count)返回一个ActiveRecord::Relation,既不是Array也不是Enumerator.调用.all该关系会将其转换为数组,并且应该使Mustache将其传递到该部分中.
| 归档时间: |
|
| 查看次数: |
2351 次 |
| 最近记录: |