HTML引入或include包含其他HTML文件

2019-05-0830770次阅读swigHTMLgulp

HTML从来没有任何方法可以在代码中包含其他HTML文件。例如包含所有页面的页眉和页脚:

<body>
   <include src="./header.html"></include>

   Content

   <include src="./footer.html"></include>
</body>

您想多了,还真没有这样的include标签。。。

 

使用PHP

<body>
   <?php include "./header.html" ?>

   Content

   <?php include "./footer.html" ?>
</body>

这将在服务器级别执行include,使得它的请求发生在服务器上的文件系统级别,因此它应该比客户端解决方案快得多。

 

使用Gulp

Gulp有各种各样的处理器可以做到这一点。一个是gulp-file-include。关于Gulp如何构建任务推荐看这里

<body>
   @@include('./header.html')

   Content

   @@include('./footer.html')
</body>

你可以这样处理它:

var fileinclude = require('gulp-file-include'),
  gulp = require('gulp');
 
gulp.task('fileinclude', function() {
  gulp.src(['index.html'])
    .pipe(fileinclude({
      prefix: '@@',
      basepath: '@file'
    }))
    .pipe(gulp.dest('./'));
});


使用Ajax

<body>
  
  <header></header>
  
  Content.
  
  <footer></footer>

</body>

您可以从相应的文件中获取页眉和页脚的内容并转储内容。

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;
  });

说到javascript,如果您使用的是javascript框架来构建站点,那么通过组件进行构建是没有问题的。例如import导入“./header.js”或<header/>。

 

使用iframes

你可以让iframe将自己的内容注入父页面,然后自行删除。

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

 

使用swig前端模板引擎

swig中include模板相对于模板根目录的路径,将一个模板渲染到当前上下文中。这也是作者当前使用的方法,这里推荐您认识一下swig前端模板引擎

{% include "./includes/header.html" %}

更多方法还可以看看这里

上一篇: Webpack4中的plugins插件概念与使用  下一篇: 再次认识requestAnimationFrame以及其polyfill库raf  

HTML引入或include包含其他HTML文件相关文章