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

1

1

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,

Carloscarlota answered 6/10, 2016 at 3:41 Comment(3)
there are multiple ways to do it. from front end or from server. at server we can manipulate the template using some template engines like ejs,jade etc. on the front end we can have the template added to DOM using JS.Brushoff
You could ajax the file in, then dump the html into the target container, reply tome if you want me to write a demoCalcify
would you mind writing this code so I can easily see it? if a.html was the master file and b.html was the child(say the banner template), how would they both be scripted?Carloscarlota
M
3

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).

Mooney answered 8/10, 2016 at 18:53 Comment(1)
hmmm, so if I wanted to import the text "hello world" from the template.html file. Where exactly would the "hello world" go? I tried putting it inside the <template></template> element but still nothing showed upCarloscarlota

© 2022 - 2024 — McMap. All rights reserved.