如何在 Meteor Blaze 模板中包含 HTML <template> 元素?

How can I include an HTML <template> element within a Meteor Blaze Template?

我正在使用 Meteor,但想使用一些使用 html 模板元素的原始 javascript/HTML 代码。

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template

当我尝试在流星模板中包含一个时:

<template name="test2">
    <template id="test3">Some stuff i will clone in javascript</template>
</template>

Meteor 显示以下错误:

While processing files with templating (for target web.browser):
client/index.html:153: Expected one of: <body>, <head>, <template>

有没有办法将这些包含在 Meteor 模板中?我知道我可以将它们包含在 body 标签中,但它有点笨拙。

事实上这不能在 Meteor 中完成,因为 Meteor 使用模板标签正是出于它设计的原因,来自您的 link:

The HTML template element is a mechanism for holding client-side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using JavaScript.

您永远不会看到 <template> 标签实际出现在 DOM 中,这将阻止您稍后在 DOM 中对其进行操作。

听起来您可能正在尝试做 Blaze 自己承担责任的事情。也许你可以告诉我们你想用你的模板做什么,我们可以告诉你如何在 Meteor 中做。

使用助手

在客户端 .js 文件中

Template.registerHelper('vanillaTemplate', () => {
    return '<template id="test3">Some stuff i will clone in javascript</template>'
})

在客户端 .html 文件

<template name="test2">
    {{> vanillaTemplate}}
</template>

只是为了提供替代解决方案,根据您的第 3 方库需要什么作为 HTML 模板,您也可以使用 <script type="text/x-template"> 而不是新的 <template>

<template name="test2">
    <script type="text/x-template" id="test3">
        Some stuff i will clone in javascript
    </script>
</template>

例如,这是 the typical solution for Vue<template> 被浏览器广泛支持之前。

优点是您可以在 HTML 中保留布局声明,并且可以完全自由地调整其内容,而不必为每个变体注册一个助手。

大多数 IDE 还原生支持在此类代码块中突出显示代码语法,而很少有人在字符串中为 HTML 提供支持。