Reputation: 22943
I have all templates in <template>
tags to improve runtime performance (avoids rendering), but I am wondering if I am using them correctly when I need their contents for compiling my Underscore templates. What I want is the string content of the DOM element, but I seem unable to access it without cloning it from the shadow DOM. I am doing this:
function compileTemplate(templateId){
var el = document.getElementById(templateId);
var templateMarkup = _.unescape(el.cloneNode(true).innerHTML);
return compiledTemplate = _.template(templateMarkup);
}
This works, but is there a more efficient that avoids cloning?
Upvotes: 2
Views: 99
Reputation: 31181
You should be able to get the innerHTML
string directly without cloning:
function compileTemplate(templateId) {
var el = document.getElementById(templateId);
var templateMarkup = _.unescape(el.innerHTML);
return compiledTemplate = _.template(templateMarkup);
}
function compileTemplate(templateId) {
var el = document.getElementById(templateId);
console.log( el.innerHTML )
}
function test() {
compileTemplate('T1')
}
<template id=T1>
HTML inside
</template>
<button onclick=test()>Compile</button>
Upvotes: 1