Mustache中使用partials的正确方法

仔细看了Mustache中的partials的用法:

base.mustache:

<h2>Names</h2>
{{#names}}
  {{> user}}
{{/names}}

user.mustache:

<strong>{{name}}</strong>

但是实际使用中总是无法成功,会报错:

var Mustache = require( 'mustache' );
Mustache.render( Fs.readFileSync( './base.mustache', { users: [ { name: 'neekey' } ] ) );

其中user.mustache 和 base.mustache在同一目录下

求指正!

阅读 5.4k
1 个回答
新手上路,请多包涵

如果单纯用文本写的话,应该按照下面的格式

const Mustache = require('mustache');
Mustache.render(
`<h2>Names</h2>
{{#names}}
  {{> user}}
{{/names}}`,
{names: { name: 'hello mustache'} },
{
   user: `<strong>{{name}}</strong>`
}
)

如果从文件中去读取

const fs = require('fs')
Mustache.render(fs.readFileSync( './base.mustache').toString(), {names: { name: 'hello mustache'} },
{
    user: fs.readFileSync( './user.mustache').toString()
});

render第三个参数传入的对象的key值要和{{> next_more}} 模版中的next_more一致

原文是这么说的:
In mustache.js an object of partials may be passed as the third argument toMustache.render. The object should be keyed by the name of the partial, and its value should be the partial text.

详情参考: https://github.com/janl/musta...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题