You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EJS无法渲染变量传入的模板,include文件找不到问题求助

Fixing "Could not find include include file" in EJS with Express

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

  1. Adjust the Path You Pass to res.render
    Instead of using a relative path from the pages directory, use a path relative to the views root. Change your render call to:

    res.render('pages/index', { template: 'partials/login' });
    
  2. Fix the EJS Include Syntax
    In your index.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 around include ensures EJS parses the function correctly:

    <%- include(template) %>
    
  3. Double-Check File Names & Structure
    Make sure your partial file is actually named login.ejs inside views/partials/—EJS automatically looks for .ejs extensions, 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 path module:
    const path = require('path');
    res.render('pages/index', { 
      template: path.join(__dirname, 'views/partials/login') 
    });
    
    But the relative-to-views-root approach is cleaner for most Express/EJS setups.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:40:51