5

After studying this Es6 tag template example:

var yo = func`${x} + ${y}\n= ${x + y}`;

one@public-node ~/es6 $ 6to5 tag.js 
"use strict";

var _taggedTemplateLiteral = function (strings, raw) {
  return Object.freeze(Object.defineProperties(strings, {
    raw: {
      value: Object.freeze(raw)
    }
  }));
};

var yo = func(_taggedTemplateLiteral(["", " + ", "\n= ", ""], ["", " + ", "\\n= ", ""]), x, y, x + y);

I see what is returned is var yo = func(strings, raw, x, y, x + y);

I understand the basics about the string literals and the x y values being inserted. What I don't understand is...when is strings used versus when is raw used? Since the function has both arrays and the user doesn't have control to tell the function when to use raw and when to use cooked(strings).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
dman
  • 10,406
  • 18
  • 102
  • 201

1 Answers1

3

The tag function func is passed just one array. That array comes from the _taggedTemplateLiteral function, which takes the incoming "strings" parameter and adds a single property to it.

The function func would be declared like this (ES5-style):

function func(strings) {
  var params = [].slice.call(arguments, 1);
  // do stuff
}

If, inside func, the code needed to use the "raw" strings, it would just access the .raw property of the "strings" variable:

function func(strings) {
  var params = [].slice.call(arguments, 1);

  var raw2 = strings.raw[2];

  // do stuff
}

So the "user" — the author of the tag function — does have control. Code in the tag function is free to examine the original content of the template parts whenever it wants. It's probably the case that tag functions that essentially implement a DSL might want to only use the raw strings, while simpler template mechanisms won't care and will be happy to use the "parsed" strings.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 2
    The proper way to access the values in ES6 would be `func(strings, ...values)` – lyschoening Jan 08 '15 at 09:18
  • 1
    @lyschoening yes, that's my understanding too. I used ES5 in the answer in order to make it clearer to most people. I probably should have noted that passing `arguments` to `[].slice` is not a good idea for code with performance requirements. – Pointy Jan 08 '15 at 14:26