我有2个HTML文件,假设a.html和b.html。在a.html中,我想包括b.html。
在JSF中,我可以这样做:
<ui:include src="b.xhtml" />
这意味着在.xhtml文件中,我可以包含b.xhtml。
我们如何在*.html文件中做到这一点?
我有2个HTML文件,假设a.html和b.html。在a.html中,我想包括b.html。
在JSF中,我可以这样做:
<ui:include src="b.xhtml" />
这意味着在.xhtml文件中,我可以包含b.xhtml。
我们如何在*.html文件中做到这一点?
当前回答
基于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
您可以根据相同的设计轻松添加更多的行为
其他回答
这是一篇很棒的文章,你可以实现公共库,只需使用下面的代码在一行中导入任何HTML文件。
<head>
<link rel="import" href="warnings.html">
</head>
你也可以试试谷歌聚合物
以下工作,如果html内容从一些文件需要包括: 例如,下面一行将在OBJECT定义出现的位置包含piece_to_include.html的内容。
...text before...
<OBJECT data="file_to_include.html">
Warning: file_to_include.html could not be included.
</OBJECT>
...text after...
参考:http://www.w3.org/TR/WD-html40-970708/struct/includes.html # h-7.7.4
作为一种替代方法,如果你可以访问服务器上的。htaccess文件,你可以添加一个简单的指令,允许php在以。html扩展名结尾的文件上被解释。
RemoveHandler .html
AddType application/x-httpd-php .php .html
现在你可以使用一个简单的php脚本来包含其他文件,比如:
<?php include('b.html'); ?>
如果你使用一些框架,比如django/bootle,他们通常会提供一些模板引擎。 假设您使用了bottle,默认的模板引擎是SimpleTemplate engine。 下面是纯html文件
$ cat footer.tpl
<hr> <footer> <p>© stackoverflow, inc 2015</p> </footer>
你可以包括页脚。TPL在你的主文件中,比如:
$ cat dashboard.tpl
%include footer
除此之外,您还可以将参数传递给dashboard .tpl。
使用includeHTML(最小js-lib:约150行)
通过HTML标签加载HTML部件(纯js) 支持加载:异步/同步,任何深度递归包括
支持的协议:http://, https://,文件:/// 支持的浏览器:IE 9+, FF, Chrome(也可能是其他)
用法:
1.在HTML文件中插入includeHTML到头部部分(或在正文结束标记之前):
<script src="js/includeHTML.js"></script>
2.在任何地方使用includeHTML作为HTML标签:
<div data-src="header.html"></div>