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

如何在ejs.renderFile中正确渲染子模板引用?

解决EJS异步模式下子模板渲染显示[object Promise]的问题

问题根源在于启用EJS的async模式后,include方法会返回一个Promise对象,普通的<%-标签无法自动解析Promise,直接输出了对象的字符串表示。Express框架内部已适配异步处理,但手动调用ejs.renderFile时需要显式处理。

修复步骤:

  1. 修改模板中的include语句,在include前添加await关键字,等待Promise解析完成:
    <%- await include('other-template'); %>
    
  2. 确保调用renderFile的上下文为异步函数,并正确使用await获取渲染结果:
    async function renderTemplate() {
      const html = await ejs.renderFile('main.ejs', {}, { async: true });
      console.log(html);
    }
    renderTemplate();
    
    注意:第二个参数为模板数据,即使无数据也需传入空对象{},避免参数位置错乱导致async选项不生效。

替代方案:

如果模板内不需要使用异步操作,可直接去掉async: true选项,此时include会同步执行,无需修改模板代码:

const html = await ejs.renderFile('main.ejs', {});

内容的提问来源于stack exchange,提问作者Arseni Mourzenko

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 19:42:02