javascripttemplates

What difference between tag <template> and script type = 'text/template'?


I need to put some HTML in JS. I saw two ways to do it: the <template>-tag and <script type = 'text/template'>, but I don't understand the difference/ what's the difference between <template>-tag and <script type = 'text/template'>?


Solution

  • <template> is used to define reusable snippets of HTML that Javascript can use. You would define it with an id, and then use it.

    <script type='text/template'> escapes the normal HTML processor because text/template is not a valid MIME type. Thus is outputs as plain-text. Learn more here: Explanation of <script type = "text/template"> ... </script>

    EDIT:

    text/html indicates that the HTML processor should be applied, formatting all HTML tags and the like.