Is it possible to interpolate a template string using key/value
s from a object in JavaScript, like string substitution in Python:
data = {"age": 18, "name": "John"}
"I'm %(name)s. I'm %(age)d years old" % data # "I'm John. I'm 18 years old"
One way that I can think of is using the with
statement,
let data = {age: 18, name: "John"}
with(data){`I'm ${name}. I'm ${age} years old`}
but with
is highly not recommended, it is neither efficient nor safe.
Is there a better way?
2
Answers
I realized that there is a major difference between Python's
string substitution
and JavsScript'stemplate string
.string
, it is only substituted when%
is called,So, the answer could be different in different scenarios:
If I simply want to interpolate a template string with a specific object named
data
, I can simply useIf I want to declare a template string, and interpolate it using different objects, I can use a function:
If I want to have some more elegent template strings, and make it somewhat programmable, I can use a tag function:
You can destruct data object:
or do this: