4

My goal is to write a tagged template function like

myTemplateTagFunction`some text ${variable} etc. etc.`

...that behaves like the default template literal function in javascript.

My first attempt was

let myTaggedTemplate = args => `${args}`

But this breaks pretty quickly...

> myTaggedTemplate`hello world ${2 + 5}`
// "hello world ,"

> `hello world ${2 + 5}`
// "hello world 7"

There must be an easier way to do this that I'm missing?

rob-gordon
  • 1,419
  • 3
  • 20
  • 38
  • 2
    With *default template literal function* you mean how a template literal would behave without it being tagged? – Emiel Zuurbier Oct 10 '20 at 21:52
  • Tagged templates don't work anything like that. Have you looked at the documentation on (for example) MDN to see that arguments are actually passed to a tagged template function? – Quentin Oct 10 '20 at 21:55
  • @Quentin I have looked at the documentation which is why my first attempt was to pass the incoming arguments back into the template literal function. If you understand them really well please lend your understanding towards an answer to this question – rob-gordon Oct 10 '20 at 22:11
  • @rob-gordon — The premise of the question doesn't really make sense. I can think of a solution (the same one as Peter as it happens), but it is, frankly, silly. Just use a template literal if you want that effect. – Quentin Oct 10 '20 at 22:14
  • 1
    @Quentin If you want to know why I'm asking then ask why I'm asking. If you want to deride the question rather then interrogate then that's on you – rob-gordon Oct 10 '20 at 22:18

3 Answers3

5

There's perhaps a shorter way to do it, but this is my approach:

const myTaggedTemplate = (strings, ...vars) => {
    let result = '';
    strings.forEach((str, i) => {
        result += `${str}${i === strings.length - 1 ? '' : vars[i]}`;
    });
    return result;
};
domenikk
  • 1,723
  • 1
  • 10
  • 12
0

How to define a tagged template function

If you define a tagged template function, it has to receive an array of strings as first argument and expressions of arbitrary number as subsequent parameters. The strings are all string between your inserted expressions (between all ${...}) and all expressions are the values of what you put into ${...}.

Example code

let numExp = 2;

function tagFunction(strings, ...expressions) {
  let returnString = "";
  for (let i = 0; i < expressions.length; i++) {
    returnString += strings[i] + expressions[i];
  }
  returnString += strings[strings.length - 1];
  return returnString;
}

console.log(
  tagFunction`Using function \"${tagFunction.name}\" with ${numExp} expressions`
);
Peter Lehnhardt
  • 4,375
  • 1
  • 14
  • 33
-1

You need to change your function:

let myTaggedTemplate = (strings,...values) => ...;

and try to follow the example in this link