We are using Mustache templates and I would like to make a preview View in our RoR web application that combines a template and some data we have stored in our database, but it does not work as I expected and after some searching on the internets (including SO!), I didn’t find any examples that included an active model.
How do you pipe the ActiveModel records to Mustache to merge with a template?
The setup:
The Schema
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
There is nothing special about the models. Both are subclassed from ActiveRecord::Base
class Bars < ActiveRecord::Base
end
class Templates < ActiveRecord::Base
end
The Controller
class TemplateController < ApplicationController
def preview
@result = Mustache.render( template.data, :bars => Bar.limit(template.data_count ) ).html_safe
end
end
The View
<%= @result %>
The Route
get 'templates/:id/preview' => 'templates#preview', :as => 'templates_preview'
The Data
y Bar.all
---
- !ruby/object:Bar
attributes:
guid: "1"
name: "test1"
- !ruby/object:Bar
attributes:
guid: "2"
name: "test2"
The Template (i’ve simplified the html for example purposes)
<html>
<head>
</head>
<body>
{{#bars}}
<a href="{{guid}}">{{name}}</a>
{{/bars}}
</body>
</html>
The Result
<html>
<head>
</head>
<body>
<a href=""></a>
</body>
</html>
The Expectation
<html>
<head>
</head>
<body>
<a href="1">test1</a><a href="2">test2</a>
</body>
</html>
I am hoping there is an easy answer to this and I am just missing it. Thanks.
Does it work if you change your controller to:
(added a call to
.allafterBar.limit(template.data_count))I’m pretty new to Mustache, but glancing very quickly through the code seems to show that it calls this for a section:
Bar.limit(template.data_count)returns anActiveRecord::Relation, which is neither anArraynor anEnumerator. Calling.allon the relation turns it into an array and should cause Mustache to pass it into the section accordingly.