Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using mustache templates, mark the correct option in a select list as selected

Tags:

mustache

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.

like image 520
newz2000 Avatar asked Jun 17 '13 18:06

newz2000


2 Answers

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" : "";
        }
    }
like image 120
ryber Avatar answered Oct 18 '22 23:10

ryber


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

like image 35
gmjordan Avatar answered Oct 18 '22 21:10

gmjordan