Template strings

To tłumaczenie jest niepełne. Pomóż przetłumaczyć ten artykuł z języka angielskiego

Napisy szablonowe to literały napisowe pozwalające na osadzone wyrażenia. Można w nich używać znaków nowej linii oraz interpolacji wyrażeń wewnątrz napisów (podstawiania wartości).


`string text`

`string text line 1
 string text line 2`

`string text ${expression} string text`

tag `string text ${expression} string text`


Template strings are enclosed by the back-tick (` `) (grave accent) character instead of double or single quotes. Template strings can contain place holders. These are indicated by the Dollar sign and curly braces (${expression}). The expressions in the place holders and the text between them get passed to a function. The default function just concatenates the parts into a single string. If there is an expression preceding the template string (tag here),  the template string is called "tagged template string". In that case, the tag expression (usually a function) gets called with the processed template string, which you can then manipulate before outputting.

Napisy wielowierszowe

Any new line characters inserted in the source are part of the template string. Using normal strings, you would have to use the following syntax in order to get multi-line strings:

console.log("string text line 1\n"+
"string text line 2");
// "string text line 1
// string text line 2"

To get the same effect with multi-line strings, you can now write:

console.log(`string text line 1
string text line 2`);
// "string text line 1
// string text line 2"

Interpolacja wyrażeń

In order to embed expressions within normal strings, you would use the following syntax:

var a = 5;
var b = 10;
console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + ".");
// "Fifteen is 15 and
// not 20."

Now, with template strings, you are able to make use of the syntactic sugar making substitutions like this more readable:

var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20."

Zagnieżdżone napisy szablonowe

In certain times, nesting a template is the easiest and perhaps more readable way to have configurable strings. Within a backticked template it is simple to allow inner backticks simply by using them inside a placeholder ${ } within the template. For instance, if condition a is true: then return this templated literal.

In ES5:

var classes = 'header'
classes += (isLargeScreen() ?
   '' : item.isCollapsed ?
     ' icon-expander' : ' icon-collapser');

In ES2015 with template literals and without nesting:

const classes = `header ${ isLargeScreen() ? '' :
    (item.isCollapsed ? 'icon-expander' : 'icon-collapser') }`;

In ES2015 with nested template literals:

const classes = `header ${ isLargeScreen() ? '' :
 `icon-${item.isCollapsed ? 'expander' : 'collapser'}` }`;

Otagowane napisy szablonowe

A more advanced form of template strings are tagged template strings. With them you are able to modify the output of template strings using a function. The first argument contains an array of string literals ("Hello " and " world" in this example). The second, and each argument after the first one, are the values of the processed (or sometimes called cooked) substitution expressions ("15" and "50" here). In the end, your function returns your manipulated string. There is nothing special about the name tag in the following example. The function name may be anything you want.

var a = 5;
var b = 10;

function tag(strings, ...values) {
  console.log(strings[0]); // "Hello "
  console.log(strings[1]); // " world "
  console.log(values[0]);  // 15
  console.log(values[1]);  // 50

  return "Bazinga!";

tag`Hello ${ a + b } world ${ a * b}`;
// "Bazinga!"

Raw strings

The special raw property, available on the first function argument of tagged template strings, allows you to access the raw strings as they were entered.

function tag(strings, ...values) {
  // "string text line 1 \\n string text line 2"

tag`string text line 1 \n string text line 2`;

In addition, the String.raw() method exists to create raw strings just like the default template function and string concatenation would create.

// "Hi\\n5!"


Napisy szablonowe NIE MOGĄ pochodzić od niezaufanych użytkowników, ponieważ mają dostęp do zmiennych i funkcji.

`${console.warn("this is", this)}`; // "this is" Window

let a = 10;
console.warn(`${a+=20}`); // "30"
console.warn(a); // 30


Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Template Literals' in that specification.
Standard Initial definition. Defined in several section of the specification: Template Literals, Tagged Templates

Kompatybilność przeglądarek

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support 41 (Yes) 34 (34) No support 28.0 No support
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support No support 41.0 34.0 (34) No support 28.0 No support

See also