Search code examples
htmltemplateshtml-importshtml5-template

Open an html file inside another html(i.e. template)


I have a banner html with a bunch of buttons(i.e. home, about,..etc.) that I'd like to set as a template. On my unique pages(say the home page), I'd like to "import" this template html file. How do I code this?

I've tried many different ways and looked it up but the closest I got was that when I imported, it had those scrollers and wasn't really "integrated" with the page. A good example of what I'm looking for is for instance, the arduino website where the top banner doesn't change.

Thanks,


Solution

  • You can use HTML Imports to import an external HTML file with a <template> element where you add the elements you want to import.

    In the main file:

    <head>
       <link rel="import" href="template.html" id="myTemplate">
    </head>
    <body>  
       <div id="container"></div>
    </body>
    

    In the template.html file:

    <template>
        <span>Hello World!</span>
    </template>
    
    <script>
        //get the imported HTML document
        var importedDoc = document.querySelector( '#myTemplate' ).import
        //get the content of the template element
        var content = importedDoc.querySelector( 'template' ).content
        //add a compy to the main page
        document.querySelector( '#container' ).appendChild( content.cloneNode( true ) ) 
    </script>
    

    In the example above, the conent of the <template> element (the <span> text "Hello World!") will be put in the <div id=container> element in the main page.

    Update 2019

    HTML Imports won't be supported natively after Chrome 73. You should then use the other solutions listed above (the polyfill, an alternate module loader, JS import, or a direct download with fetch).