把手:第一次运行时未发现部分问题

我有一个节点脚本来编译使用句柄模板。 这是我的模板:

<div class="header"> <h1>{{title}}</h1> </div> <div class="body"> <p>{{body}}</p> </div> <div class="footer"> <div><a href="http://twitter.com/{{author.twitter}}">{{autor.name}}</a> </div> <ul> {{#each tags}} <li>{{this}}</li> {{/each}} </ul> {{> example_partial}} </div> 

相应的部分是

 <div> <p> Hi, I am a partial! </p> </div> 

和JS

 var handlebars = require('handlebars'), fs = require('fs'); var data = { title: 'practical node.js', author: '@azat_co', tags: ['express', 'node', 'javascript'] } data.body = process.argv[2]; fs.readFile('handlebars-example-partial.html', 'utf-8', function(error, source) { handlebars.registerPartial('example_partial', source); }); fs.readFile('handlebars-example.html', 'utf-8', function(error, source){ var template = handlebars.compile(source); var html = template(data); console.log(html) }); 

当我第一次使用node app.js通过节点运行脚本时,我无法弄清楚,我得到以下错误:

 /Users/rahul/stencil/node_modules/handlebars/dist/cjs/handlebars/runtime.js:266 throw new _exception2['default']('The partial ' + options.name + ' could not be found'); ^ Error: The partial example_partial could not be found at Object.invokePartial (/Users/rahul/stencil/node_modules/handlebars/dist/cjs/handlebars/runtime.js:266:11) at Object.invokePartialWrapper [as invokePartial] (/Users/rahul/stencil/node_modules/handlebars/dist/cjs/handlebars/runtime.js:68:39) at Object.eval (eval at createFunctionContext (/Users/rahul/stencil/node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js:254:23), <anonymous>:16:28) at main (/Users/rahul/stencil/node_modules/handlebars/dist/cjs/handlebars/runtime.js:173:32) at ret (/Users/rahul/stencil/node_modules/handlebars/dist/cjs/handlebars/runtime.js:176:12) at ret (/Users/rahul/stencil/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:525:21) at /Users/rahul/stencil/examples/standalone_v1/handlebars-example.js:29:14 at tryToString (fs.js:414:3) at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:401:12) 

但是,当我再次运行该程序时,它工作正常,我得到预期的输出(不改变任何东西)。 有人可以向我解释我做错了什么吗?

问题在于你编译使用它的模板的时候,你的偏好实际上并没有被注册。 这是因为fs.readFile是一个asynchronous操作。

一个解决scheme是使用fs.readFileSync

 var partial = fs.readFileSync('handlebars-example-partial.html', 'utf-8'); handlebars.registerPartial('example_partial', partial); fs.readFile('handlebars-example.html', 'utf-8', function(error, source){ var template = handlebars.compile(source); var html = template(data); console.log(html) }); 

或者你可以把它全部放在部分注册的callback中:

 fs.readFile('handlebars-example-partial.html', 'utf-8', function(error, partial) { handlebars.registerPartial('example_partial', partial); fs.readFile('handlebars-example.html', 'utf-8', function(error, template) { var compiled = handlebars.compile(template); var html = compiled(data); console.log(html); }); }