I have a server-rendered form that uses Mustache templates. When the form is submitted, if there is an error, I reshow the form along with some errors. I want the fields to be re-populated with the same values that were submitted.
However, I'm not sure how to mark the proper item from the select list. Here's my data:
errors = {'required': ['name']},
fields = {name: 'Matt', option: 'sales'};
And I use a template like this:
<form method="post" action="submitform" id="submitform">
<input type="text" id="name" name="name" value="{{fields.name}}">
<select name="contact" id="contact">
<option value="support">Support request</option>
<option value="sales">Sales help</option>
<option value="press">Press information</option>
</select>
<button type="submit" name="submit">Send message</button>
</form>
In this example, I'd expect the second option in the select to have a selected
attribute. I'd prefer not to use Javascript in this case. Any suggestions?
I like the concept of logic-less templates, as provided by Mustache, but I'm still wrapping my head around the actual details.
In a tool with a little more logic, for example Django templates, I might say:
<option value="sales" {%if fields.option == 'sales'}selected{% endif %}>
Thanks for any tips.
Mustache is not entirely logic-less. It's just mostly logic-less.
Have a field on your model for each row called "selected" and just output it like this:
<form method="post" action="submitform" id="submitform">
<select name="contact" id="contact">
{{#options}}
<option name="{{name}}" {{selected}}>{{name}}</option>
{{/options}}
</select>
<button type="submit" name="submit">Send message</button>
</form>
your model would look like this (this is Java BTW, you can do the same in whatever:
public class Option {
public String name;
public String selected;
public Option(String name, boolean seleted){
this.name = name;
this.selected = seleted ? "selected" : "";
}
}
based on the suggestions from ryber, I've added a library to handle this as well. It includes some annotations (updated docs forthcoming)
https://github.com/gmjordan/options.mustache.java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With