可以在类似于 css 的 html 文件中包含 `templates` 吗?

can one include `templates` in a html file similar to css?

与 html templates 合作。在代码方面,很难为每个 html 文件保留正确的模板集。

是否可以有一个模板文件,很像 css 的文件,它包含在 html 文件的 head 部分?

例如,要补充 head 中的 style 部分,可以 link 到样式表,例如

<link rel="stylesheet" type="text/css" href="mystyle.css" >

我的应用程序使用了 templates 的多个集合。它们是否可以像样式表一样处理,即 linked 到单独的文件中,或者每个 template 定义是否需要直接成为原始 html 文件的一部分?

http://www.html5rocks.com/en/tutorials/webcomponents/imports/

虽然

你需要HTML 5
<head>
  <link rel="import" href="/path/to/imports/stuff.html">
</head>

不幸的是,

<head>
  <link rel="import" href="/path/to/imports/stuff.html">
</head>

有效。

整个 stuff.html 作为 html 作为 head 的一部分卡在那里,并且出于所有实际目的无法访问。

换句话说,template defined instuff.htmlcannot be found usingdocument.querySelector()`,因此脚本不可用。

fwiw,我真的不明白 import 它现在工作方式的任何优点 - 它需要剥离(而不是添加)所有外部 html 在将内容附加到 head 之前 - 不是它的当前操作。

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 )
} ()

原回答

假设我们想在一个名为 templates.html.

的单独文件中导入一堆 <template>

在(主)主页index.html,我们可以通过HTML导入文件:

<link rel="import" href="templates.html" id="templates">

在导入的文件templates.html中,根据需要添加一个或多个模板:

<template id="t1">
     <div>content for template 1</div>
</template>

<template id="t2">
     content for template 2
</template>

导入的文档可从 <link> 元素的 import 属性 获得。你可以在上面使用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>

注意:您可以将上述脚本放在主文档中,也可以放在导入的文档中,因为导入文件中的 <script>s 会立即执行已解析(在下载时)。