Wednesday, 28 February 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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...