简体   繁体   中英

Mustache JS templating and unknown properties

I'm trying to use mustache JS templates dynamically. I'll have an array of templates like so:

var tmpls = [
   '<p>{{name}}</p>',
   '<p><b>{{car}}</b></p>'
];

and then I want to pick the correct template based on the index of something... which I can do like:

var stuff = {
      name: 'bob'
}

$.mustache(tmpls[index], stuff);

but I'm not quite sure how to fill the values based on something else such as input IDs and their values:

<input type="text" id="name" value="Bob" />
<input type="text" id="car" value="Corsa" />

$.mustache(tmpls[index], {
    $('input').eq(0).attr('id') : $('input').eq(0).val()
});

I guess I'm trying to create an object to pass mustache dynamically. The property names are the IDs of the input fields and the values are from the input field.

Is this possible?

Thanks, Dom

One possible way to build your stuff object is by iterating through the elements using .each() :

var stuff = {};

$('input').each(function() {
    stuff[$(this).attr('id')] = $(this).val();
});

$.mustache(tmpls[index], stuff);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM