我有2个HTML文件,假设a.html和b.html。在a.html中,我想包括b.html。

在JSF中,我可以这样做:

<ui:include src="b.xhtml" />

这意味着在.xhtml文件中,我可以包含b.xhtml。

我们如何在*.html文件中做到这一点?


当前回答

我还有一个解

在javascript中使用Ajax

以下是Github repo中的解释代码 https://github.com/dupinder/staticHTML-Include

基本思想是:

index . html

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <script src='main.js'></script>


</head>
<body>
    <header></header>

    <footer></footer>
</body>
</html>

main.js

fetch("./header.html")
  .then(response => {
    return response.text()
  })
  .then(data => {
    document.querySelector("header").innerHTML = data;
  });

fetch("./footer.html")
  .then(response => {
    return response.text()
  })
  .then(data => {
    document.querySelector("footer").innerHTML = data;
  });

其他回答

在我看来,最好的解决方案使用jQuery:

a.html:

<html> 
  <head> 
    <script src="jquery.js"></script> 
    <script> 
    $(function(){
      $("#includedContent").load("b.html"); 
    });
    </script> 
  </head> 

  <body> 
     <div id="includedContent"></div>
  </body> 
</html>

b.html:

<p>This is my include file</p>

这个方法简单明了地解决了我的问题。

jQuery .load()文档在这里。

你试过iFrame注入吗?

它在文档中注入iFrame并删除自己(它应该在HTML DOM中)

<iframe src=“header.html” onload=“this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove()”></iframe>

问候

您可以使用HTML Imports的填充(https://www.html5rocks.com/en/tutorials/webcomponents/imports/)或简化的解决方案 https://github.com/dsheiko/html-import

例如,在你导入HTML块的页面上:

<link rel="html-import" href="./some-path/block.html" >

该块可以有自己的导入:

<link rel="html-import" href="./some-other-path/other-block.html" >

导入器用加载的HTML替换指令,就像SSI一样

这些指令将在你加载这个小JavaScript时自动提供:

<script async src="./src/html-import.js"></script>

它将在DOM准备就绪时自动处理导入。此外,它还公开了一个API,您可以使用该API手动运行、获取日志等等。享受:)

下面是我使用Fetch API和async函数的方法

<div class="js-component" data-name="header" data-ext="html"></div>
<div class="js-component" data-name="footer" data-ext="html"></div>

<script>
    const components = document.querySelectorAll('.js-component')

    const loadComponent = async c => {
        const { name, ext } = c.dataset
        const response = await fetch(`${name}.${ext}`)
        const html = await response.text()
        c.innerHTML = html
    }

    [...components].forEach(loadComponent)
</script>

如果你使用一些框架,比如django/bootle,他们通常会提供一些模板引擎。 假设您使用了bottle,默认的模板引擎是SimpleTemplate engine。 下面是纯html文件

$ cat footer.tpl
<hr> <footer>   <p>&copy; stackoverflow, inc 2015</p> </footer>

你可以包括页脚。TPL在你的主文件中,比如:

$ cat dashboard.tpl
%include footer

除此之外,您还可以将参数传递给dashboard .tpl。