html使用include引入其他页面文件

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

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

   Content

   <include src="./footer.html"></include>
</body>
<!-- html没有这样的include标签 -->

方式:
1、使用PHP

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

   Content

   <?php include "./footer.html" ?>
</body>
<!-- 这将在服务器级别执行include,
使得它的请求发生在服务器上的文件系统级别,
因此它应该比客户端解决方案快得多。 -->

2、使用Gulp

Gulp有各种各样的处理器可以做到这一点。一个是gulp-file-include。

<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('./'));
});

3、使用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/>。

4、使用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>

5、使用swig前端模板引擎

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

{% include "./includes/header.html" %}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值