Skip to content

Commit

Permalink
Add section on template literal tags (mbeaudru#53)
Browse files Browse the repository at this point in the history
* Add section on template literal tags

Fix mbeaudru#52.

* Fixed code indents, added sample and ref
  • Loading branch information
Glutnix authored and mbeaudru committed Oct 2, 2017
1 parent ff13f65 commit 7a1286f
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -1027,6 +1027,48 @@ const name = "Nick";
- [String interpolation - ES6 Features](http://es6-features.org/#StringInterpolation)
- [ES6 Template Strings - Addy Osmani](https://developers.google.com/web/updates/2015/01/ES6-Template-Strings)

### Tagged template literals

Template tags are *functions that can be prefixed to a [template literal](#template-literals)*. When a function is called this way, the first parameter is an array of the *strings* that appear between the template's interpolated variables, and the subsequent paremeters are the interpolated values. Use a spread operator `...` to capture all of them. [(Ref: MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals).

> **Note :** A famous library named [styled-components](https://www.styled-components.com/) heavily relies on this feature.
Below is a toy example on they work.
```js
function highlight(strings, ...values) {
const interpolation = strings.reduce((prev, next) => {
return prev + next + (values.shift() || "");
}, "");

return `<mark>${interpolation}</mark>`;
}

const condiment = "jam";
const meal = "toast";

highlight`I like ${condiment} on ${meal}.`;
// "<mark>I like jam on toast.</mark>"
```

A more interesting example:
```js
function comma(strings, ...values) {
return strings.reduce((prev, next) => {
let value = values.shift() || [];
value = value.join(", ");
return prev + next + value;
}, "");
}

const snacks = ['apples', 'bananas', 'cherries'];
comma`I like ${snacks} to snack on.`;
// "I like apples, bananas, cherries to snack on."
```

#### External resources
- [Wes Bos on Tagged Template Literals](http://wesbos.com/tagged-template-literals/)
- [Library of common template tags](https://github.com/declandewet/common-tags)

### Imports / Exports

ES6 modules are used to access variables or functions in a module explicitly exported by the modules it imports.
Expand Down

0 comments on commit 7a1286f

Please sign in to comment.