phwa4563 phwa4563 - 2 years ago 399
HTML Question

Render HTML Tag attribute using mustache

In my mustache template I do have something like:

<div {{attr}}="{{attrVal}}"></div>


Rendering this using

Mustache.render(template, {attr : 'data-test', attrVal : 'test'})


does produce

<div ="test"></div>


I expect to get something like

<div data-test="test"></div>


Isn't it possible to render attribute name inside of a tag using Mustache?

UPDATE

I figured out the problem. I define my HTML Mustache Templates inside custom
<template>
tags in my document. For example:

<template id='myTemplate'>
<div {{dataAttr}}="{{dataAttrValue}}"></div>
</template>


When getting the template using
document.querySelector("#myTemplate").innerHTML
the browser does convert the
{{dataAttr}}
to
{{dataattr}}
because attributes are case insensitiv. So calling

Mustache.render(
document.querySelector("#myTemplate").innerHTML,
{ dataAttr : 'data-attr', dataAttrValue : 'test'}
);


Results in

<div ="test"></div>

Answer Source

What you're doing there actually looks correct. As an example, check out:

http://jsbin.com/rilihasise/1/edit?html,js,console

Is it possible template isn't defined properly?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download