[英]EJS nightmare — cannot include external view
There never seems to be an easy way of including external files in EJS.似乎从来没有一种简单的方法可以在 EJS 中包含外部文件。
I have my project structured like this.我的项目结构是这样的。 So simple it hurts:
如此简单,它很痛苦:
/lib/ejs-template.ejs
/views/home.ejs
/views/header.ejs
Inside home.ejs
I must include header.ejs
.在
home.ejs
,我必须包含header.ejs
。 I am mercifully following their documentation: https://ejs.co/#docs and include the file this way because " Includes are relative to the template with the include call ",我很幸运地遵循了他们的文档: https://ejs.co/#docs并以这种方式包含文件,因为“包含与包含调用的模板相关”,
<%- include("header") %>
Inside ejs-template.ejs
I am compiling the template like this:在
ejs-template.ejs
,我正在编译这样的模板:
module.exports = (target, vars = {})=>{
return Ejs.compile( Fs.readFileSync(`${__dirname}/../views/${target}.ejs`, {encoding: 'utf-8'}), {
views: [ Path.resolve('../views') ],
})(vars)
}
Yet I get this error!然而我得到这个错误!
Error: ejs:38
36| <body>
37|
>> 38| <%- include("header") %>
39|
40| <main class="container">
41| <h4>Some stuff</h4>
Could not find the include file "header"
at getIncludePath ([redacted]\server\node_modules\ejs\lib\ejs.js:183:13)
at includeFile ([redacted]\server\node_modules\ejs\lib\ejs.js:309:19)
at include ([redacted]\server\node_modules\ejs\lib\ejs.js:690:16)
at eval (eval at compile ([redacted]\server\node_modules\ejs\lib\ejs.js:662:12), <anonymous>:12:17)
at anonymous ([redacted]\server\node_modules\ejs\lib\ejs.js:692:17)
at module.exports ([redacted]\server\util\ejs-template.js:13:7)
at [redacted]\server\route\site.js:13:18
at Layer.handle [as handle_request] ([redacted]\server\node_modules\express\lib\router\layer.js:95:5)
at next ([redacted]\server\node_modules\express\lib\router\route.js:137:13)
at module.exports ([redacted]\server\middleware\isLoggedIn.js:8:9) {
path: ''
}
I have set the views path in the compiling options.我在编译选项中设置了视图路径。 I have tried with/without path.
我试过有/没有路径。 I've also tried with
root
set at the same exact views path.我也尝试过在相同的确切视图路径上设置
root
。
What am I missing?我错过了什么? The documentation is lax and offers no clues regarding this.
文档松散,没有提供有关此的任何线索。
Seems it was a path issue.似乎是路径问题。 I had to set it up like this:
我不得不这样设置:
views: [ Path.resolve(__dirname, '../views') ],
Kudos to https://github.com/mde/ejs/issues/594#issuecomment-812518617感谢 https://github.com/mde/ejs/issues/594#issuecomment-812518617
as I understood you are facing issue with include header portion in main view file.据我了解,您在主视图文件中遇到包含 header 部分的问题。 I used below code for same.
我使用下面的代码相同。
<body>
<%- include("header"}) %>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
<button>Button</button>
</body>
above script is you home.ejs
and you can create header.ejs
.上面的脚本是你
home.ejs
,你可以创建header.ejs
。 you can include like above你可以像上面一样包括
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.