1
+ // 1. Template Literals
2
+ // are string literals that can stretch across multiple lines and include interpolated expressions (inserted via ${···}):
3
+
4
+ // const firstName = `Jane`;
5
+ // console.log(`Hello ${firstName}!
6
+ // How are
7
+ // you?
8
+ // `);
9
+
10
+ // 2. Tagged template literals (short: tagged templates) are created by mentioning a function before a template literal
11
+ // The common usages of tag functions is getting the raw data out of template string.
12
+
13
+ // function fmtDate(strings, date) {
14
+ // const str0 = strings[0], str1 = strings[1];
15
+ // console.log(strings)
16
+ // const strDate = new Intl.DateTimeFormat('en-US').format(date);
17
+ // console.log(`${str0}${strDate}${str1}`);
18
+ // return `${str0}${strDate}${str1}`;
19
+ // }
20
+ //
21
+ // fmtDate`Today is ${new Date()}`;
22
+
23
+ // console.log(String.raw`first ${new Date()}`)
24
+
25
+ // 3. A tag function for HTML templating
26
+
27
+ // function html(templateObject, ...substs) {
28
+ // console.log(substs);
29
+ // const raw = templateObject.raw;
30
+ //
31
+ // let result = '';
32
+ //
33
+ // substs.forEach((subst, i) => {
34
+ // let lit = raw[i];
35
+ // if (Array.isArray(subst)) {
36
+ // subst = subst.join('');
37
+ // }
38
+ //
39
+ // if (lit.endsWith('!')) {
40
+ // subst = htmlEscape(subst);
41
+ // lit = lit.slice(0, -1);
42
+ // }
43
+ // result += lit;
44
+ // result += subst;
45
+ // });
46
+ // result += raw[raw.length - 1]; // (A)
47
+ // return result;
48
+ // }
49
+ //
50
+ // function htmlEscape(str) {
51
+ // return str.replace(/&/g, '&') // first!
52
+ // .replace(/>/g, '>')
53
+ // .replace(/</g, '<')
54
+ // .replace(/"/g, '"')
55
+ // .replace(/'/g, ''')
56
+ // .replace(/`/g, '`');
57
+ // }
58
+ //
59
+ // const tmpl = addrs => html`
60
+ // <table>
61
+ // ${addrs.map(addr => html`
62
+ // <tr><td>!${addr.first}</td></tr>
63
+ // <tr><td>!${addr.last}</td></tr>
64
+ // `)}
65
+ // </table>
66
+ // `;
67
+ // const data = [
68
+ // { first: '<Jane>', last: 'Bond' },
69
+ // { first: 'Lars', last: '<Croft>' },
70
+ // ];
71
+ // console.log(tmpl(data));
0 commit comments