我有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文件中做到这一点?
当前回答
如果你使用一些框架,比如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。
其他回答
一个简单的服务器端包含指令,包括在同一文件夹中找到的另一个文件,如下所示:
<!--#include virtual="a.html" -->
你也可以试试:
<!--#include file="a.html" -->
你可以用JavaScript的jQuery库来实现这一点,就像这样:
HTML:
<div class="banner" title="banner.html"></div>
JS:
$(".banner").each(function(){
var inc=$(this);
$.get(inc.attr("title"), function(data){
inc.replaceWith(data);
});
});
请注意banner.html应该位于您的其他页面所在的相同域下,否则您的网页将拒绝banner.html文件,因为跨源资源共享政策。
另外,请注意,如果您使用JavaScript加载内容,谷歌将无法对其进行索引,因此对于SEO而言,这并不是一个好方法。
我的解决方案类似于上面的lolo。但是,我通过JavaScript的文档插入HTML代码。编写而不是使用jQuery:
a.html:
<html>
<body>
<h1>Put your HTML content before insertion of b.js.</h1>
...
<script src="b.js"></script>
...
<p>And whatever content you want afterwards.</p>
</body>
</html>
研究:
document.write('\
\
<h1>Add your HTML code here</h1>\
\
<p>Notice however, that you have to escape LF's with a '\', just like\
demonstrated in this code listing.\
</p>\
\
');
我反对使用jQuery的原因是jQuery.js的大小约为90kb,我想保持加载的数据量尽可能小。
为了得到正确转义的JavaScript文件,你可以使用下面的sed命令:
sed 's/\\/\\\\/g;s/^.*$/&\\/g;s/'\''/\\'\''/g' b.html > escapedB.html
或者只是使用以下方便的bash脚本作为Github上的Gist发布,它自动完成所有必要的工作,将b.html转换为b.js: https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6
感谢Greg Minshall改进的sed命令,它还转义了反斜杠和单引号,这是我最初的sed命令没有考虑到的。
另外,对于支持模板字面量的浏览器,以下方法也适用:
研究:
document.write(`
<h1>Add your HTML code here</h1>
<p>Notice, you do not have to escape LF's with a '\',
like demonstrated in the above code listing.
</p>
`);
仅使用HTML是不可能将HTML文件包含在另一个HTML文件中。这里有一个很简单的方法。使用这个JS库你可以很容易地做到这一点。只需使用以下代码:
<script> include('path/to/file.html', document.currentScript) </script>
另一种方法是使用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>