【问题标题】:Fill variable in exported file在导出的文件中填充变量
【发布时间】:2020-12-17 16:04:14
【问题描述】:

我正在尝试导出一个包含电子邮件信息的文件和一个“名称”变量,在将其导入另一个 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')

【问题讨论】:

    标签: javascript variables


    【解决方案1】:

    你可以导出一个函数来输出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');
    

    【讨论】:

    • 非常感谢!这成功了,没想到。
    猜你喜欢
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 2016-05-27
    • 2020-01-26
    相关资源
    最近更新 更多