使用ejs模版嵌入页眉/页脚模版是报错

问题描述:使用ejs模版时,在模版中嵌入页面/页脚模版,运行后,报如下错误:

SyntaxError: Unexpected identifier in D:\Code\Web\StudyOrTest\later\views\articles.ejs while compiling ejs

If the above error is not helpful, you may want to try EJS-Lint:
https://github.com/RyanZim/EJS-Lint
Or, if you meant to create an async function, pass `async: true` as an option.
    at new Function (<anonymous>)
    at Template.compile (D:\Code\Web\StudyOrTest\later\node_modules\ejs\lib\ejs.js:661:12)
    at Object.compile (D:\Code\Web\StudyOrTest\later\node_modules\ejs\lib\ejs.js:396:16)
    at handleCache (D:\Code\Web\StudyOrTest\later\node_modules\ejs\lib\ejs.js:233:18)
    at tryHandleCache (D:\Code\Web\StudyOrTest\later\node_modules\ejs\lib\ejs.js:272:16)
    at View.exports.renderFile [as engine] (D:\Code\Web\StudyOrTest\later\node_modules\ejs\lib\ejs.js:489:10)
    at View.render (D:\Code\Web\StudyOrTest\later\node_modules\express\lib\view.js:135:8)
    at tryRender (D:\Code\Web\StudyOrTest\later\node_modules\express\lib\application.js:640:10)
    at Function.render (D:\Code\Web\StudyOrTest\later\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (D:\Code\Web\StudyOrTest\later\node_modules\express\lib\response.js:1012:7)

esj模版代码如下:

<% include head %>
<ul>
    <% articles.forEach((article) => { %>
        <li>
            <a href="/articles/<% article.id %>">
                <%= article.title %>
            </a>
        </li>
    <% }); %>
</ul>
<% include foot %>

解决方案:将<% include head %>改为<%- include(‘head‘) %>,修改后的代码如下:

<%- include(‘head‘) %>
<ul>
    <% articles.forEach((article) => { %>
        <li>
            <a href="/articles/<% article.id %>">
                <%= article.title %>
            </a>
        </li>
    <% }); %>
</ul>
<%- include(‘foot‘) %>

参考资料:

  1. SyntaxError: Unexpected identifier when using ejs in nodejs

使用ejs模版嵌入页眉/页脚模版是报错

上一篇:一键部署apache


下一篇:洞察——风格注意力网络(SANet)在任意风格迁移中的应用