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

Node.js中ejs renderFile渲染模板时关联CSS文件样式不生效问题

问题原因

  • 你代码中定义的CSS路径变量options没有传入ejs.renderFile方法,EJS渲染时无法读取关联的样式文件
  • 外部<link>引用的CSS在nodeHtmlToImage生成图片时无法识别相对路径,会出现资源加载失败的情况
  • 邮件场景下外部CSS本身兼容性极差,基本都会被邮箱服务商拦截

解决步骤

  1. 优先使用内联样式,将Bootstrap和自定义CSS的内容直接注入到EJS模板中,避免外部资源加载问题
  2. 修正路径拼接逻辑,使用path.join适配多操作系统路径规则
  3. 给nodeHtmlToImage添加加载等待配置,确保样式渲染完成后再生成图片

修正后代码示例

const fs = require('fs');
const path = require('path');
const ejs = require('ejs');
const nodeHtmlToImage = require('node-html-to-image');

function sendBusinessQuotaEmail() {
  const templatePath = path.join(process.cwd(), "/emailTemplates/businessQuotaEmailTemplate/businessQuotaEmailTemplate.ejs");
  // 读取bootstrap和自定义CSS文件内容
  const bootstrapCss = fs.readFileSync(path.join(process.cwd(), "你存放bootstrap.min.css的实际路径"), 'utf8');
  const customCss = fs.readFileSync(path.join(process.cwd(), "/emailTemplates/businessQuotaEmailTemplate/businessQuotaEmailTemplate.css"), 'utf8');
  
  // 将CSS内容传入模板数据
  const templateData = {
    abc: 'test',
    bootstrapCss: bootstrapCss,
    customCss: customCss
  };
  
  console.log('here sendBusinessQuotaEmail');
  ejs.renderFile(templatePath, templateData, (err, html) => {
    if (err) {
      console.log('ejs render file error on line # 7209', err);
      return;
    }
    console.log('html', html);
    nodeHtmlToImage({
      output: path.join(process.cwd(), "/tempFiles/download/abc.jpg"),
      html: html,
      waitUntil: 'load' // 等待所有资源渲染完成再截图
    }).then(() => {
      console.log('The image was created successfully!');
    });
  });
}

EJS模板修改

在你的EJS模板<head>标签内添加如下代码,注入样式内容:

<head>
  <style>
    <%- bootstrapCss %>
    <%- customCss %>
  </style>
</head>

注意必须使用<%-语法,不要用<%=,避免CSS特殊字符被转义导致样式失效

内容的提问来源于stack exchange,提问作者Ahmer Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:27:02