Rendering this wit...">

Display HTML Tag attribute with mustache

In my mustache pattern, I have something like:

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

Rendering this with

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

creates

 <div ="test"></div> 

I expect to get something like

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

Can't display attribute name inside tag using Mustache?

UPDATE

I understood the problem. I define my Mustache HTML templates inside custom <template> tags in my document. For instance:

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

When retrieving a template using document.querySelector("#myTemplate").innerHTML browser converts {{dataAttr}} to {{dataAttr}} because the attributes are insensitiv. Therefore challenge

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

Results in

 <div ="test"></div> 
+6
source share
2 answers

We hope this piece of code helps you.

 var template = document.querySelector("#template").innerHTML; //Mustache.parse(template); // optional, speeds up future uses var rendered = Mustache.render(template, { attr: "data-test", attrVal: "test" }); document.querySelector("#target").innerHTML = rendered; 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.2.1/mustache.js"></script> <body> <div id="target">Loading...</div> <template id="template" > <textarea style="width:300px"> <div {{attr}}="{{attrVal}}"></div> </textarea> </template> </body> 
0
source

I am heading the same issue. Try the single [']:

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

.....

0
source