Strapi邮件模板使用EJS可输出内容但条件语句失效问题
解决Strapi邮件EJS模板条件语句未解析的问题
以下是几个直接的排查和解决方向:
1. 确认Strapi邮件配置已启用EJS模板引擎
在config/plugins.js(或config/plugins.ts)的邮件配置中,必须明确指定模板引擎为EJS,并配置正确的模板目录:
module.exports = ({ env }) => ({ email: { config: { provider: 'your-provider', // 如nodemailer等邮件提供商 providerOptions: { // 对应提供商的配置参数 }, settings: { defaultFrom: 'your-email@example.com', defaultReplyTo: 'your-email@example.com', template: { engine: 'ejs', // 关键:指定使用EJS引擎 dir: './src/templates/emails', // 模板文件存放路径 }, }, }, }, });
2. 检查模板文件扩展名
确保你的邮件模板文件后缀为.ejs(比如confirmation.ejs),而非.html。如果使用.html后缀,Strapi不会触发EJS的语法解析逻辑。
3. 正确调用邮件发送方法
在钩子或服务中发送邮件时,必须通过Strapi邮件服务传入模板及上下文变量,不要直接读取未渲染的文件内容发送:
// 示例:用户创建后发送确认邮件的钩子 module.exports = { async afterCreate(event) { const { result } = event; await strapi.plugins['email'].services.email.send({ to: result.email, subject: '账号确认', template: 'confirmation', // 对应templates/emails/confirmation.ejs文件 context: { // 传入模板所需的变量 username: result.username, confirmUrl: `https://your-domain.com/confirm/${result.id}` }, }); }, };
4. 验证EJS语法完整性
你的示例语法本身正确,但需确保模板中无语法错误(比如标签未闭合、括号不匹配)。可以先用最简代码测试:
<% if(true){ %> <h1>foo</h1> <% } else{ %> <h1>bar</h1> <% } %>
5. 适配Strapi版本
如果使用Strapi v4,邮件插件的配置逻辑和v3有差异,需确保配置符合对应版本的官方规范。比如v4中邮件配置的顶层键是email,而v3可能为email-plugin。
如果以上步骤无效,可尝试手动调用EJS库渲染模板后再发送:
const ejs = require('ejs'); const fs = require('fs'); const path = require('path'); // 手动读取并渲染模板 const templatePath = path.join(__dirname, '../../templates/emails/confirmation.ejs'); const templateContent = fs.readFileSync(templatePath, 'utf8'); const renderedHtml = ejs.render(templateContent, { username: result.username }); // 发送渲染后的HTML内容 await strapi.plugins['email'].services.email.send({ to: result.email, subject: '账号确认', html: renderedHtml, });
内容的提问来源于stack exchange,提问作者binzram
相关产品推荐
相关产品推荐

