TIL Tagged Templates
POSTED ON:
TAGS: mdn javascript image
Today I learned of Tagged Templates!
Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.
The MDN example:
const person = "Mike";
const age = 28;
function myTag(strings, personExp, ageExp) {
const str0 = strings[0]; // "That "
const str1 = strings[1]; // " is a "
const str2 = strings[2]; // "."
const ageStr = ageExp > 99 ? "centenarian" : "youngster";
// We can even return a string built using a template literal
return `${str0}${personExp}${str1}${ageStr}${str2}`;
}
// This breaks the string into all of its wild pieces.
const output = myTag`That ${person} is a ${age}.`;
console.log(output);
MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates
The html example:
via https://www.reddit.com/r/webdev/comments/10wap56/did_you_know_about_javascript_tag_functions/
Related TILs
Tagged: mdn