是否可以从其他文件导入模板?我能够导入javascript和样式表,但无法弄清楚如何导入html模板.
例如:
我在templates.html中定义了各种内容项模板
<template id="hello>Hello {{ li.name }}</template>
<template id="hey">Hey!</template>
Run Code Online (Sandbox Code Playgroud)
然后,我想重新使用list.html中的模板
<link rel="import" href="templates.html">
<polymer-element name="list" attributes="type,data">
<template>
<template repeat="{{ li in items_in_data }}">
<template bind ref="hey"></template>
<template bind ref="{{ type }}"></template>
</template>
</template>
</polymer-element>
Run Code Online (Sandbox Code Playgroud)
最后,在app.html中
<list data="items.json" type="hello"></list>
Run Code Online (Sandbox Code Playgroud)
如果我将templates.html中的内容放入list.html,它可以正常工作.但是,使用时似乎没有加载或引用<link rel="import">.有任何想法吗?
部分解决方案:以下内容适用于 chrome,但不适用于 polyfill 浏览器(例如 firefox)。需要查看 polyfill 代码来弄清楚如何处理已链接文件中的链接。
问题在于导入的内容并未插入到文档中,而只是可供使用。有关更多详细信息,请参阅HTML5 Rocks 导入 - 使用内容。您可以在链接文件中找到所有模板并将它们插入到聚合物元素的文档片段中:
var importDoc = document.currentScript.ownerDocument;
var link = importDoc.querySelector('.myimports');
var templates = link.import.querySelectorAll('template');
for (var i=0;i<templates.length;i++) {
importDoc.head.appendChild(templates[i]);
}
Run Code Online (Sandbox Code Playgroud)
<template id="hello">Hello World!</template>
<template id="goodbye">See you tomorrow</template>
Run Code Online (Sandbox Code Playgroud)
<link class="myimports" rel="import" href="demo-templates.html">
<polymer-element name="demo-importTemplates-list">
<template>
<template repeat="{{ li in data }}">
<h1>{{li}}</h1>
<template bind ref="hello"></template> -- <template bind ref="goodbye"></template>
</template>
</template>
<script>
Polymer({
data: ['first','second','third']
});
// http://www.html5rocks.com/en/tutorials/webcomponents/imports/#usingcontent
// http://www.html5rocks.com/en/tutorials/webcomponents/imports/#include-templates
var importDoc = document.currentScript.ownerDocument;
var link = importDoc.querySelector('.myimports');
var templates = link.import.querySelectorAll('template');
for (var i=0;i<templates.length;i++) {
importDoc.head.appendChild(templates[i]);
}
</script>
</polymer-element>
Run Code Online (Sandbox Code Playgroud)
<html lang="en">
<head>
<script src="../../webcomponents/bower_components/webcomponentsjs/webcomponents.min.js"></script>
<link rel="import" href="../../webcomponents/bower_components/polymer/polymer.html">
<link rel="import" href="demo-importTemplates-list.html">
<title>demo-importTemplates</title>
</head>
<body>
<demo-importTemplates-list type="hello"></demo-importTemplates-list>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)