如何将 ejs 转换为车把?

How do I convert ejs to handlebars?

我正在尝试将此 ejs 代码转换为车把。我正在上教程,所以它给我带来了一些问题。我很乐意得到任何帮助

<% if(typeof errors!= 'undefined') { %>
<%    errors.forEach(function(error){ %>
<p> <%= error.msg %></p>
<%    })        %>
<% } %>

这是我的转换:

{{#if typeof errors !== "undefined"}}
  {{#each error}}
    <p>{{error.msg}}</p>
  {{/each}}
{{/if}}

但是我一直收到这个错误:

Error: Parse error on line 1:
{{#if typeof errors !== "undefined"}}  
--------------------^
Expecting 'CLOSE_RAW_BLOCK', 'CLOSE', 'CLOSE_UNESCAPED', 'OPEN_SEXPR', 'CLOSE_SEXPR', 'ID', 'EQUALS', 'OPEN_BLOCK_PARAMS', 'STRING', 'NUMBER', 'BOOLEAN', 'UNDEFINED', 'NULL', 'DATA', 'SEP', got 'INVALID'
    at Parser.parseError (/home/bunny/Tales/node_modules/handlebars/dist/cjs/handlebars/compiler/parser.js:267:19)
    at Parser.parse (/home/bunny/Tales/node_modules/handlebars/dist/cjs/handlebars/compiler/parser.js:336:30)
    at parseWithoutProcessing (/home/bunny/Tales/node_modules/handlebars/dist/cjs/handlebars/compiler/base.js:46:33)
    at HandlebarsEnvironment.parse (/home/bunny/Tales/node_modules/handlebars/dist/cjs/handlebars/compiler/base.js:52:13)
    at compileInput (/home/bunny/Tales/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:508:19)
    at ret (/home/bunny/Tales/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:517:18)
    at Object.invokePartial (/home/bunny/Tales/node_modules/handlebars/dist/cjs/handlebars/runtime.js:334:12)
    at Object.invokePartialWrapper [as invokePartial] (/home/bunny/Tales/node_modules/handlebars/dist/cjs/handlebars/runtime.js:84:39)
    at Object.eval [as main] (eval at createFunctionContext (/home/bunny/Tales/node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js:262:23), <anonymous>:10:31)
    at main (/home/bunny/Tales/node_modules/handlebars/dist/cjs/handlebars/runtime.js:208:32)
    at ret (/home/bunny/Tales/node_modules/handlebars/dist/cjs/handlebars/runtime.js:212:12)
    at ret (/home/bunny/Tales/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:519:21)
    at ExpressHandlebars._renderTemplate (/home/bunny/Tales/node_modules/express-handlebars/lib/express-handlebars.js:250:9)
    at ExpressHandlebars.<anonymous> (/home/bunny/Tales/node_modules/express-handlebars/lib/express-handlebars.js:173:15)

此外,我想将这个 ejs 部分文件添加到我的把手中,这就是我所做的。我不知道我有多正确:

Ejs:
<%- include ('./partials/messages') %>

Handlebars:
{{> _messages}}

您的 handlebars 语法看起来不正确,您的转换应该是:

{{#if errors }}
  {{#each errors}}
    <p>{{ this.msg }}</p>
  {{/each}}
{{/if}}

{{#if errors }} 检查 errorundefined 还是 [] (https://handlebarsjs.com/guide/builtin-helpers.html#if)

此外,this 用于引用被迭代的元素 (https://handlebarsjs.com/guide/builtin-helpers.html#each)。