你可以这样做。背后的想法是将HTML文件包含在HTML文件中。我至少可以通过3种方式说明这种情况的发生,但我个人完全只是验证了第三种方式。
首先出现的是一个jQuery next sample is taken from this thread
a.html:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
b.html:
<p> This is my include file </p>
另一种解决方案,我发现这里并没有需要jQuery但仍未测试:there is a small function
我的解决方案是纯HTML5,可能在旧版浏览器中不受支持,但我不关心它们。
添加在HTML的头,链接到你的HTML模板与
<link rel="import" href="html/templates/Hello.html">
添加模板代码中的Hello.html。不是使用这个工具功能:
loadTemplate: function(templateName)
{
var link = document.querySelector('link[rel="import"][href="html/templates/' + templateName + '.html"]');
var content = link.import;
var script = content.querySelector('script').innerHTML || content.querySelector('script').innerText;
return script;
}
最后,调用在你需要它的功能:随时可以使用
var tpl = mobileUtils.loadTemplate('hello');
this.templates.compiledTpl = Template7.compile(tpl);
现在你已经编译模板。
======= UPDATE
建设我的项目的ios后,我发现,进口环节没有从所有的浏览器都支持但我没有做它iphone工作。所以我尝试了方法2。它的工作原理,但你可能会看到它得到请求,我不喜欢。 jquery的负载似乎有相同的缺陷。
于是我想出了方法号4
<iframe id="iFrameId" src="html/templates/template1.html" style="display:none"></iframe>
,现在我的loadTemplate功能
loadTemplate: function(iframeId, id)
{
var iFrame = document.getElementById(iframeId);
if (!iFrame || !iFrame.contentDocument) {
console.log('missing iframe or iframe can not be retrieved ' + iframeId);
return "";
}
var el = iFrame.contentDocument.getElementById(id);
if (!el) {
console.log('iframe element can not be located ' + id);
return "";
}
return el.innerText || el.innerHTML;
}
这是否意味着它不可能或很难有那些模板代码为html格式的另一个HTML文件? – SonicC
您是否考虑过使用服务器端编码?例如,使用PHP,可以将HTML代码放在不同的PHP文件中。我们这种方法可以同时具备以下两种模式:(1)HTML格式的模板和(2)单独的文件模板。 –