I’m using Sinatra and a client-side template called Dust.js (akin to Mustache) to build a simple form flow. In the initial state, form labels are being passed via JSON
{ "fields" : [ { "title" : "First Name", "name" : "fn" }, { "title" : "Last Name", "name": "ln" } ] }
and interpreted by Dust:
{#fields} <label>{title}: <input type="text" name="{name}" /></label> {/fields}
This is all well and good. After the form is submitted though, I want to reuse the {title} but also iterate through the user-entered values using {name} as the key. What would be nice is to be able to write something like this — even though it won’t work since <%= params[] %> is evaluated before {name}:
<ul>
{#fields}
<li><b>{title}</b>: <%= params[{name}] %></li>
{/fields}
</ul>
And this is where I’m stuck. Even if I create an instance variable in the controller and pass it all of the param values, I’m still not sure how to sync up iteration over both the {title} variables and the params.values.
This is as far as I’ve gotten:
# controller
post '/submit' do
@v = []
params.values.each do |v|
@v << "#{v}"
end
erb :submit
end
<!-- view -->
<ul>
{#fields}
<% @v.each do |k| %>
<li><b>{title}</b>: <%= k %></li>
<% end %>
{/fields}
</ul>
Any help would be very much appreciated!
I’ll answer my own question, in case it’s helpful to anyone else out there. Basically, the controller needs to pass the values (in the right order) to the view, then Dust.js can do its thing.