EJS无法渲染变量传入的模板,include文件找不到问题求助
Hey there, let's work through this EJS include issue step by step! The error you're seeing happens because EJS handles dynamic include paths differently than static ones, especially with your project structure.
Let's Break Down the Problem
Your project structure has views/pages/index.ejs trying to include a partial from views/partials/login.ejs. When you pass ../partials/login as the template variable, EJS doesn't resolve this relative path the way you expect—instead of looking relative to pages/, it treats the path as relative to the root of your views directory, so it's actually searching for ../partials/login outside the views folder, which doesn't exist.
Solution Steps
Adjust the Path You Pass to
res.render
Instead of using a relative path from thepagesdirectory, use a path relative to theviewsroot. Change your render call to:res.render('pages/index', { template: 'partials/login' });Fix the EJS Include Syntax
In yourindex.ejs, use<%- include(template) %>instead of<% include (template) %>. The<%-tag outputs the raw HTML from the partial (avoiding HTML escaping), and removing the extra space aroundincludeensures EJS parses the function correctly:<%- include(template) %>Double-Check File Names & Structure
Make sure your partial file is actually namedlogin.ejsinsideviews/partials/—EJS automatically looks for.ejsextensions, but missing the file or having a typo here will still throw the "not found" error.
Additional Checks
- You already set
view cache: false, which is great—this ensures any path changes you make take effect immediately without restarting the server. - If you still want to use absolute paths for clarity, you can construct the full path using Node's
pathmodule:
But the relative-to-views-root approach is cleaner for most Express/EJS setups.const path = require('path'); res.render('pages/index', { template: path.join(__dirname, 'views/partials/login') });
Why This Works
EJS resolves dynamic include paths (using variables) relative to the root views directory you configured in Express, not relative to the current template file. By switching to partials/login, you're pointing directly to the partial within the views structure, which EJS can find easily.
内容的提问来源于stack exchange,提问作者Rahul Padalkar

