访问变量值

时间:2017-08-07 08:26:04

标签: javascript html

我正在使用readFileSync访问一个html文件,如下所示

 var content = fs.readFileSync("client/index.html", "utf-8");

并将内容传递给html。

Students.afterRemote('create', function(ctx, result, next) {
 loopback.Email.send({
            to: result.email,
            from: "person1@something.com",
            subject: "Thanks for choosing Us",
            text: "text message",
            html: content,
            var: {
                myVar1: 'a custom value'
            },
            headers: {
                "X-My-Header": "My Custom header"
            }
        })
        .then(function(response) {
        })
        .catch(function(err) {
        });
}

在我的html文件中,我有这段代码

    result.name + "<p> Your account is created successfully.Thanks for creating an account</p>"

在电子邮件中,它没有给我result.name的值。它显示result.name。我怎样才能获得它的价值?感谢

1 个答案:

答案 0 :(得分:0)

当你在字符串中看到类似JavaScript代码的内容时,它仍然只是该字符串的一部分。它不会像JavaScript代码一样执行。

var result = { name: "bar" };
var string = `    result.name + "<p> Your account is created successfully.Thanks for creating an account</p>"`;
console.log(string);

如果你想使用变量,那么你需要用JavaScript编写它们,而不是用你读入变量的文本文件。

var result = { name: "bar" };
var string = `<p> Your account is created successfully.Thanks for creating an account</p>`;
var output = result.name + string;
console.log(output);

您可以将占位符放在文件中,然后使用替换调用...

var result = { name: "bar" };
var string = `<<<name>>><p> Your account is created successfully.Thanks for creating an account</p>`;
string = string.replace("<<<name>>>", result.name);
console.log(string);

...但是在那个阶段,您正在创建自己的模板语言,应该像an off the shelf option

那样选择Nunjucks

var result = { name: "bar" };
var template = `{{ name }}<p> Your account is created successfully.Thanks for creating an account</p>`;

console.log(nunjucks.renderString(template, result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/nunjucks/3.0.1/nunjucks.min.js"></script>