首页 > 解决方案 > 在导出的文件中填充变量

问题描述

我正在尝试导出一个包含电子邮件信息的文件和一个“名称”变量,在将其导入另一个 javascript 文件时该变量将被替换。

const emailTemplate = {
    subject: 'test',
    body_html: `
    <html>
    <title>
    hey guys
    </title>
    <body>
    Hey ${name}
    </html>
    `
}

module.exports = {
    emailTemplate 
}

但是,我不确定如何在将 name 变量导入其他地方时填充它,并且无法真正查找它。关于在这种情况下我能做什么的任何想法?谢谢!

这就是我在另一个文件中导入它的方式。

const emailTemplate = require('./email/template')

标签: javascriptvariables

解决方案


您可以导出一个函数来输出 html。

function getBodyHtml(name) {
    // your desired content
    return `
<html>
<title>
hey guys
</title>
<body>
Hey ${name}
</html>`
}

const emailTemplate = {
    subject: 'test',
    getBodyHtml,
}

module.exports = {
    emailTemplate,
};

然后,在另一个文件中调用该函数。

// anotherFile.js
const emailTemplate = require('./email/template');

// call the function with the `name` variable in order to get the template
const myTemplate = emailTemplate.getBodyHtml('insert name here');

推荐阅读