简体   繁体   中英

Pass the value of external variables in a tagged template

tag is a function that accepts a template string:

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. 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}`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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