Skip to content

Commit 7a1286f

Browse files
Glutnixmbeaudru
authored andcommitted
Add section on template literal tags (mbeaudru#53)
* Add section on template literal tags Fix mbeaudru#52. * Fixed code indents, added sample and ref
1 parent ff13f65 commit 7a1286f

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

readme.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1027,6 +1027,48 @@ const name = "Nick";
10271027
- [String interpolation - ES6 Features](http://es6-features.org/#StringInterpolation)
10281028
- [ES6 Template Strings - Addy Osmani](https://developers.google.com/web/updates/2015/01/ES6-Template-Strings)
10291029

1030+
### Tagged template literals
1031+
1032+
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).
1033+
1034+
> **Note :** A famous library named [styled-components](https://www.styled-components.com/) heavily relies on this feature.
1035+
1036+
Below is a toy example on they work.
1037+
```js
1038+
function highlight(strings, ...values) {
1039+
const interpolation = strings.reduce((prev, next) => {
1040+
return prev + next + (values.shift() || "");
1041+
}, "");
1042+
1043+
return `<mark>${interpolation}</mark>`;
1044+
}
1045+
1046+
const condiment = "jam";
1047+
const meal = "toast";
1048+
1049+
highlight`I like ${condiment} on ${meal}.`;
1050+
// "<mark>I like jam on toast.</mark>"
1051+
```
1052+
1053+
A more interesting example:
1054+
```js
1055+
function comma(strings, ...values) {
1056+
return strings.reduce((prev, next) => {
1057+
let value = values.shift() || [];
1058+
value = value.join(", ");
1059+
return prev + next + value;
1060+
}, "");
1061+
}
1062+
1063+
const snacks = ['apples', 'bananas', 'cherries'];
1064+
comma`I like ${snacks} to snack on.`;
1065+
// "I like apples, bananas, cherries to snack on."
1066+
```
1067+
1068+
#### External resources
1069+
- [Wes Bos on Tagged Template Literals](http://wesbos.com/tagged-template-literals/)
1070+
- [Library of common template tags](https://github.com/declandewet/common-tags)
1071+
10301072
### Imports / Exports
10311073

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

0 commit comments

Comments
 (0)