cc *_*ung 3 html javascript html5-template html-imports
使用HTML templates.代码方面,很难为每个html文件保留正确的模板集.
是有可能有模板(S)的文件,很像一个文件css,一个在包括head一节的html文件?
例如,为了补充该style部分head,可以链接到样式表,例如,
<link rel="stylesheet" type="text/css" href="mystyle.css" >
我的应用程序使用了几个集合templates.它们可以像样式表那样处理,即链接到单独的文件中,还是每个template定义都需要直接作为原始html文件的一部分?
想象一下,我们想<template>在一个名为templates.html的单独文件中导入一堆s 。
在(主)主页index.html 中,我们可以通过 HTML Imports 导入文件:
<link rel="import" href="templates.html" id="templates">
Run Code Online (Sandbox Code Playgroud)
在导入的文件templates.html 中,根据需要添加一个或任意多个模板:
<template id="t1">
<div>content for template 1</div>
</template>
<template id="t2">
content for template 2
</template>
Run Code Online (Sandbox Code Playgroud)
导入的文档可从元素的import属性中获得<link>。你可以使用querySelector它。
<script>
//get the imported document in doc:
var link = document.querySelector( 'link#templates' )
var doc = link.import
//fetch template2 1 and 2:
var template1 = doc.querySelector( '#t1' )
var template2 = doc.querySelector( '#t2' )
</script>
Run Code Online (Sandbox Code Playgroud)
注意:您可以将上述脚本放在主文档中,也可以放在导入的文档中,因为<script>导入文件中的s 会在解析后立即执行(在下载时)。
2020 更新
现在 HTML 导入已被弃用,您可以使用fetch()下载 HTML 代码:
void async function () {
//get the imported document in templates:
var templates = document.createElement( 'template' )
templates.innerHTML = await ( await fetch( 'templates.html' ) ).text()
//fetch template2 1 and 2:
var template1 = templates.content.querySelector( '#t1' )
var template2 = templates.content.querySelector( '#t2' )
console.log( template2 )
} ()
Run Code Online (Sandbox Code Playgroud)
http://www.html5rocks.com/en/tutorials/webcomponents/imports/
你需要HTML 5
<head>
<link rel="import" href="/path/to/imports/stuff.html">
</head>
Run Code Online (Sandbox Code Playgroud)