我知道我正在尝试回答一个老问题。通过将模板字符串嵌入到静态 HTML 文档中,这是非常可行的,该文档包含在属性 type="text/x-handlebars-template" 的元素中。这被称为微模板。由于 type 属性,浏览器不会尝试执行脚本。例如 -
<script id="list-template" type="text/x-handlebars-template">
<p>YUI is brought to you by:</p>
<ul>
{{#items}}
<li><a href="{{url}}">{{name}}</a></li>
{{/items}}
</ul>
</script>
完成后,我们必须编译然后通过数据对象渲染它。
<script>
YUI().use('handlebars', 'node-base', function (Y) {
// Extract the template string and compile it into a reusable function.
var source = Y.one('#list-template').getHTML(),
template = Y.Handlebars.compile(source),
html;
// Render the template to HTML using the specified data.
html = template({
items: [
{name: 'pie', url: 'http://pieisgood.org/'},
{name: 'mountain dew', url: 'http://www.mountaindew.com/'},
{name: 'kittens', url: 'http://www.flickr.com/search/?q=kittens'},
{name: 'rainbows', url: 'http://www.youtube.com/watch?v=OQSNhk5ICTI'}
]
});
// Append the rendered template to the page.
Y.one('body').append(html);
});
有关详细信息,请参阅此处 - http://yuilibrary.com/yui/docs/handlebars/