Wednesday, February 28, 2018

javascript - Template literal trapped in a string variable

I also had this problem sometimes when I have my labels variables in another file, and those labels should have a template literal. I this cases I usually use a workaround to simulate this behaviour (take this code as a guide :D )




labels.js:



export default:{
labelWithSpeudoliteral: "text to {{change}}"
}


MyHelper.js:



    generateLiteral(s, params) {

const entries = Object.entries(params);
let sentence = s;
entries.forEach((entry) => {
const literal = `{{${entry[0]}}}`
sentence = sentence.replace(literal, entry[1]);
}
)
return sentence;
}



Now in my code I use this helper the following way:



console.log(generateLiteral(labels.labelWithSpeudoliteral, {'change': 'literal'})


And the result of the label should be:



text to literal



As you can see using the {{ }} symbols as marks, generateLiteral() use them and the params received to change the text value with the template literal. It is not the best way, but I hope it can help you.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...