简体   繁体   English

在标记模板中传递外部变量的值

[英]Pass the value of external variables in a tagged template

tag is a function that accepts a template string: tag是一个接受模板字符串的函数:

function tag(strings) {
    console.log(strings.raw);
}

tag`Output something`

It works fine.它工作正常。 Now the problem is, I have an external variable and I want to pass the value of the variable to the template string, something like this:现在的问题是,我有一个外部变量,我想将变量的值传递给模板字符串,如下所示:

function tag(strings) {
    console.log(strings.raw);
}

const key = "a"
tag`The value of key: ${key}` // I need it to output "The value of key: a", but the actual output is "The value of key: "

It doesn't work as expected because javascript thinks key is one of tag 's parameters.它不能按预期工作,因为 javascript 认为keytag的参数之一。 How to solve this problem?如何解决这个问题呢?

You need to have another parameter that accepts the key value.您需要有另一个接受键值的参数。

function tag( strings, key ) {
    console.log(strings[0] + key);
}

const key = "a"
tag`The value of key: ${key}`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM