How can I render a template, mustache.js for example, using data returned by a jQuery selector? Like so:
var imgs = $('img'),
arrayOfImgs = { img : $.makeArray(imgs) },
template = "{{#img}} <span> {{.}} </span> {{/img}}",
html = Mustache.render(template, arrayOfImgs);
$('.portfolio').html(html);
That doesn't work as $.makeArray(imgs)
returns array of img
objects, is there a work around?
You'll have to return the HTML as string, which is easily done with a $.map and returning this.outerHTML
var imgs = $('img'),
arrayOfImgs = $.map(imgs, function(el) { return el.outerHTML; }),
template = "{{#img}} <span> {{.}} </span> {{/img}}",
html = Mustache.render(template, arrayOfImgs);
$('.portfolio').html(html);
Just use var imgs = $('img')
. It's already an array of img html tags. I don't know how Mustache works.
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.