0

Is there a way to continue working with a template after the initial expression/assignment?

As expected, this works:

const testTag = (strings, ...values) => console.log(strings, values);
testTag `${'this'}${'is'}${'test'}`;
> ["", "", "", ""], raw: ["", "", "", ""]
> ["this", "is", "test"]

This doesn't:

const testTag = (strings, ...values) => console.log(strings, values);
const testLiteral = `${'this'}${'is'}${'test'}`;
testTag testLiteral;
> Uncaught SyntaxError: Unexpected identifier

const testTag = (strings, ...values) => console.log(strings, values);
const testLiteral = `${'this'}${'is'}${'test'}`;
testTag `${testLiteral}`;
> ["", ""], raw: ["", ""]
> ["thisistest"]

const testTag = (strings, ...values) => console.log(strings, values);
const testLiteralMaker = () => `${'this'}${'is'}${'test'}`;
testTag `${testLiteralMaker()}`;
> ["", ""], raw: ["", ""]
> ["thisistest"]

const testTag = (strings, ...values) => console.log(strings, values);
const testLiteralMaker = () => `${'this'}${'is'}${'test'}`;
testTag(testLiteralMaker());
> thisistest
> []

const testTag = (strings, ...values) => console.log(strings, values);
const testLiteralMaker = () => `${'this'}${'is'}${'test'}`;
testTag(...testLiteralMaker());
> t
> ["h", "i", "s", "i", "s", "t", "e", "s", "t"]

((strings, ...values) => console.log(strings, values))(`${'this'}${'is'}${'test'}`)
> thisistest
> []

((strings, ...values) => console.log(strings, values))((() => `${'this'}${'is'}${'test'}`)())
> thisistest
> []

I'm interested in a way that I can write reusable code using template literals, but I cannot understand how two functions can meaningfully share them.

BEVR1337
  • 623
  • 4
  • 10
  • 2
    Template literal or not, the line `testTag testLiteral;` is a syntax error. – ibrahim mahrir Dec 14 '18 at 18:25
  • 2
    ... and template literals are supposed to be used once to generate a string, hence the word "literal" in their name. – ibrahim mahrir Dec 14 '18 at 18:28
  • @ibrahimmahrir Of course it is! That is why I showed the console output as such. – BEVR1337 Dec 14 '18 at 18:28
  • 1
    Tagged template functions have no requirement to return a string. (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates) Additionally, there is merit in wanting to sequence tagged templates in order to separate concerns. For example, the first tag is used to prettify units, and the second is used to create html nodes. – BEVR1337 Dec 14 '18 at 18:34
  • seems like a dupe of https://stackoverflow.com/questions/30003353/can-es6-template-literals-be-substituted-at-runtime-or-reused – gman Jun 25 '19 at 20:06

0 Answers0