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

江枫思渺然 提交于 2020-01-15 09:16:29

问题


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,


回答1:


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



来源:https://stackoverflow.com/questions/39887153/open-an-html-file-inside-another-htmli-e-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!