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

在JSF中,我可以这样做:

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

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

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


当前回答

PHP是一种服务器级脚本语言。它可以做很多事情,但一个流行的用途是在页面中包含HTML文档,这与SSI非常相似。与SSI一样,这是一种服务器级技术。如果你不确定你的网站上是否有PHP功能,请联系你的主机提供商。

下面是一个简单的PHP脚本,你可以使用它在任何支持PHP的网页上包含HTML片段:

将网站常用元素的HTML保存到单独的文件中。例如,导航部分可以保存为navigation.html或navigation.php。 使用下面的PHP代码将该HTML包含在每个页面中。

<?php require($DOCUMENT_ROOT . "navigation.php"); ?>

在希望包含该文件的每个页面上使用相同的代码。 确保将突出显示的文件名更改为包含文件的名称和路径。

其他回答

基于https://stackoverflow.com/a/31837264/4360308的回答 我用Nodejs (+ express + cheerio)实现了这个功能,如下所示:

HTML (index . HTML)

<div class="include" data-include="componentX" data-method="append"></div>
<div class="include" data-include="componentX" data-method="replace"></div>

JS

function includeComponents($) {
    $('.include').each(function () {
        var file = 'view/html/component/' + $(this).data('include') + '.html';
        var dataComp = fs.readFileSync(file);
        var htmlComp = dataComp.toString();
        if ($(this).data('method') == "replace") {
            $(this).replaceWith(htmlComp);
        } else if ($(this).data('method') == "append") {
            $(this).append(htmlComp);
        }
    })
}

function foo(){
    fs.readFile('./view/html/index.html', function (err, data) {
        if (err) throw err;
        var html = data.toString();
        var $ = cheerio.load(html);
        includeComponents($);
        ...
    }
}

Append ->将内容包含到div中

Replace ->替换div

您可以根据相同的设计轻松添加更多的行为

插入指定文件的内容。

<!--#include virtual="filename.htm"-->

一个非常老的解决方案满足了我当时的需求,但下面是如何做到标准兼容的代码:

<!--[if IE]>
<object classid="clsid:25336920-03F9-11CF-8FD0-00AA00686F13" data="some.html">
<p>backup content</p>
</object>
<![endif]-->

<!--[if !IE]> <-->
<object type="text/html" data="some.html">
<p>backup content</p>
</object>
<!--> <![endif]-->

另一种方法是使用Fetch API和Promise

<html>
 <body>
  <div class="root" data-content="partial.html">
  <script>
      const root = document.querySelector('.root')
      const link = root.dataset.content;

      fetch(link)
        .then(function (response) {
          return response.text();
        })
        .then(function (html) {
          root.innerHTML = html;
        });
  </script>
 </body>
</html>

通过Html5rocks教程检查HTML5导入 在聚合物项目

例如:

<head>
  <link rel="import" href="/path/to/imports/stuff.html">
</head>