Search code examples
javascripthtmlhtml5-template

How can I save a <template> for a second use?


I'm trying to properly use HTML5 templates in a webpage. However, I discovered that when I take the content of a template and put it into some section of the webpage, the template is emptied and the same action can't be performed again. How do I ensure the template isn't emptied, or should I be using a different technique?

Example

HTML:

<div>
    <button id="replace-button">Click to show template</button>
    <div id="holder"></div>
</div>

<template id="my-template">Hooray! Now, note that when you try again, this area will be blank.</template>

JavaScript:

$("#replace-button").click(replaceWithTemplate);

function replaceWithTemplate(event) {
    $("#holder").html($("#my-template")[0].content);
}

Live demo: http://jsfiddle.net/Supuhstar/y33a9/


Solution

  • "How do I ensure the template isn't emptied?"

    After you use the content of the template, the template becomes "live" (as Eric terms it). You can't read the content of a "live" template. Thus, if you want to reuse a template, you should clone the template's content and never activate the original template in the first place.


    jQuery

    As Will mentioned, you can use jQuery's .clone() method to accomplish this. You could also use the .html() method with the same results. (Fiddle)

    Pure JavaScript

    As Dan Davis mentioned in a comment, you can also use the .cloneNode(true) method of the template node to perform a deep copy of the template. Thus, you don't activate the original template, you active the clone. (Fiddle)

    Alternatively, the MDN Docs use .importNode() to copy template content.