我的 node.js 应用程序中有一个 Handlebars / mustache 布局文件,如下所示:
{{> header}}
{{> navbar}}
{{{body}}}
{{> footer-user}}
{{> footer}}
既然所有五行都包含,那么两种类型的包含之间有什么区别吗?我可以将 {{{body}}} 替换为 {{>body}} 或将 {{> header}} 替换为 {{{header}}} 吗?它们似乎都没有逃脱包含的 html。最佳实践是什么?
最佳答案
语法 {{> name}}
用于部分,即包含另一个模板:
Handlebars allows for template reuse through partials. Partials are normal Handlebars templates that may be called directly by other templates.
而 {{{name}}}
用于包含数据而不转义它。如果您希望转义数据,可以使用 {{name}}
:
Handlebars HTML-escapes values returned by a {{expression}}. If you don't want Handlebars to escape a value, use the "triple-stash", {{{.
所以它们是不同的东西。
{{{body}}}
引用应用程序提供的当前上下文中的 body
属性(或者它可以引用辅助函数,但这不是案例在这里)。
如果代码中有 {{>body}}
,则意味着您有一个名为 body
的模板,您希望 Handlebars 加载该模板。
请注意,如果您正确使用 Handlebars,则所有部分都需要通过调用 Handlebars.registerPartial
进行注册(如果您的项目使用 express-handlebars
,它会完成所有操作为您服务,这样您就不会在代码中找到它)。
Handlebars 的文档可以在 handlebarsjs.com 找到.
关于 mustache {{{partial}}} 与 {{>partial}},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29976892/