1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
|
---
title: Template literals
slug: Web/JavaScript/Reference/Template_literals
tags:
- Template
translation_of: Web/JavaScript/Reference/Template_literals
---
<div>{{JsSidebar("More")}}</div>
<p>템플릿 리터럴은 내장된 표현식을 허용하는 문자열 리터럴입니다. 여러 줄로 이뤄진 문자열과 문자 보간기능을 사용할 수 있습니다. 이전 버전의 ES2015사양 명세에서는 "template strings" (템플릿 문자열) 라고 불려 왔습니다.</p>
<h2 id="Syntax">Syntax</h2>
<pre class="syntaxbox ">`string text`
`string text line 1
string text line 2`
`string text ${expression} string text`
tag `string text ${expression} string text`
</pre>
<h2 id="Description">Description</h2>
<p>템플릿 리터럴은 이중 따옴표 나 작은 따옴표 대신 백틱(` `) (<a href="http://en.wikipedia.org/wiki/Grave_accent">grave accent</a>) 을 이용합니다. 템플릿 리터럴은 또한 플레이스 홀더를 이용하여 표현식을 넣을 수 있는데, 이는 $와 중괄호( <code>$ {expression}</code> ) 로 표기할 수 있습니다. 플레이스 홀더 안에서의 표현식과 그 사이의 텍스트는 함께 함수로 전달됩니다. 기본 함수는 단순히 해당 부분을 단일 문자열로 연결시켜 줍니다. 템플릿 리터럴 앞에 어떠한 표현식이 있다면(여기에서는 태그), 템플릿 리터럴은 "태그가 지정된 템플릿"이라고 불리게 됩니다. 이 때, 태그 표현식 (주로 함수)이 처리된 템플릿 리터럴과 함께 호출되면, 출력하기 전에 조작할 수 있습니다. 템플릿 리터럴 안에서 백틱 문자를 사용하려면 백틱 앞에 백슬러쉬(\)를 넣으십시오.</p>
<pre class="brush: js ">`\`` === "`" // --> true</pre>
<h3 id="Multi-line_strings">Multi-line strings</h3>
<p>source 내에 삽입되는 newline characters(\n)은 template literal의 일부가 됩니다.</p>
<p>일반 string 들을 사용하여, multi-line strings 들을 얻기 위해서는 아래와 같은 문법을 사용해야 할 것입니다.</p>
<pre class="brush: js ">console.log("string text line 1\n"+
"string text line 2");
// "string text line 1
// string text line 2"</pre>
<p>같은 효과를 template literal을 통해 얻기 위해서는, 아래와 같이 적을 수 있습니다.</p>
<pre class="brush: js ">console.log(`string text line 1
string text line 2`);
// "string text line 1
// string text line 2"</pre>
<h3 id="Expression_interpolation표현식_삽입법">Expression interpolation(표현식 삽입법)</h3>
<p>표현식(expression)을 일반 문자열(normal strings)에 삽입하기 위해서, 당신은 다음의 문법을 사용할 수 있을 것입니다.</p>
<pre class="brush: js ">var a = 5;
var b = 10;
console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + ".");
// "Fifteen is 15 and
// not 20."</pre>
<p>template literals을 이용하면, 이를 더욱 읽기 쉽도록 다음과 같은 문법 설탕(syntactic sugar) 을 활용할 수 있습니다.</p>
<pre class="brush: js ">var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20."</pre>
<h3 id="Nesting_templates">Nesting templates</h3>
<p>특정한 경우 템플릿을 중첩하는 것이 구성 가능한 문자열을 읽는 읽기 가장 쉬운 방법입니다. 백 스페이스 템플릿 내에서 템플릿 내의 자리 표시자<code>${}</code>에 내부 백틱을 사용하는 것이 쉽습니다. 예를 들어, 조건 a가 참이면:이 템플릿을 문자 그대로 반환합니다.</p>
<p>In ES5:</p>
<pre ><code>var classes = 'header'
classes += (isLargeScreen() ?
'' : item.isCollapsed ?
' icon-expander' : ' icon-collapser');</code></pre>
<p>ES2015에서 중첩(nesting)없이 템플릿 리터럴 사용한 경우:</p>
<pre ><code>const classes = `header ${ isLargeScreen() ? '' :
(item.isCollapsed ? 'icon-expander' : 'icon-collapser') }`;</code></pre>
<p>ES2015에서 중첩된(nested) 템플릿 리터럴을 사용한 경우:</p>
<pre ><code>const classes = `header ${ isLargeScreen() ? '' :
`icon-${item.isCollapsed ? 'expander' : 'collapser'}` }`;</code></pre>
<h3 id="Tagged_templates">Tagged templates</h3>
<p>template literals 의 더욱 발전된 한 형태는 <em>tagged</em> templates 입니다. 태그를 사용하면 템플릿 리터럴을 함수로 파싱 할 수 있습니다. 태그 함수의 첫 번째 인수는 문자열 값의 배열을 포함합니다. 나머지 인수는 표현식과 관련됩니다. 결국 함수는 조작 된 문자열을 반환 할 수 있습니다 (또는 다음 예제에서 설명하는 것과 완전히 다른 결과를 반환 할 수 있습니다). function 이름은 원하는 어떤 것이든 가능합니다.</p>
<pre ><code>var person = 'Mike';
var age = 28;
function myTag(strings, personExp, ageExp) {
var str0 = strings[0]; // "that "
var str1 = strings[1]; // " is a "
// 사실 이 예제의 string에서 표현식이 두 개 삽입되었으므로
// ${age} 뒤에는 ''인 string이 존재하여
// 기술적으로 strings 배열의 크기는 3이 됩니다.
// 하지만 빈 string이므로 무시하겠습니다.
// var str2 = strings[2];
var ageStr;
if (ageExp > 99){
ageStr = 'centenarian';
} else {
ageStr = 'youngster';
}
// 심지어 이 함수내에서도 template literal을 반환할 수 있습니다.
return str0 + personExp + str1 + ageStr;
}
var output = myTag`that ${ person } is a ${ age }`;
console.log(output);
// that Mike is a youngster</code></pre>
<p>다음 예시에서 보여지듯이, Tag function 들은 string 을 반환할 필요는 없습니다.</p>
<pre class="brush: js ">function template(strings, ...keys) {
return (function(...values) {
var dict = values[values.length - 1] || {};
var result = [strings[0]];
keys.forEach(function(key, i) {
var value = Number.isInteger(key) ? values[key] : dict[key];
result.push(value, strings[i + 1]);
});
return result.join('');
});
}
var t1Closure = template`${0}${1}${0}!`;
t1Closure('Y', 'A'); // "YAY!"
var t2Closure = template`${0} ${'foo'}!`;
t2Closure('Hello', {foo: 'World'}); // "Hello World!"
</pre>
<h3 id="Raw_strings">Raw strings</h3>
<p>태그 지정된 템플릿의 첫 번째 함수 인수에서 사용할 수있는 특별한 <code>raw</code> property을 사용하면 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Using_special_characters_in_strings">escape sequences</a> 처리하지 않고 원시 문자열을 입력 한대로 액세스 할 수 있습니다.</p>
<pre ><code>function tag(strings) {
console.log(strings.raw[0]);
}
tag`string text line 1 \n string text line 2`;
// logs "string text line 1 \n string text line 2" ,
// including the two characters '\' and 'n'</code></pre>
<p>추가로, default template function 과 string 병합으로 생성될 것 같은 raw string 을 생성하기 위한 {{jsxref("String.raw()")}} method가 존재합니다.</p>
<pre ><code>var str = String.raw`Hi\n${2+3}!`;
// "Hi\n5!"
str.length;
// 6
str.split('').join(',');
// "H,i,\,n,5,!"</code></pre>
<h3 id="Tagged_templates_and_escape_sequences">Tagged templates and escape sequences</h3>
<h4 id="ES2016_behavior">ES2016 behavior</h4>
<p>ECMAScript 2016에서 tagged templates은 다음 escape sequences의 규칙을 따릅니다.</p>
<ul>
<li>Unicode escapes started by "\u", for example <code>\u00A9</code></li>
<li>Unicode code point escapes indicated by "\u{}", for example <code>\u{2F804}</code></li>
<li>Hexadecimal escapes started by "\x", for example <code>\xA9</code></li>
<li>Octal literal escapes started by "\" and (a) digit(s), for example <code>\251</code></li>
</ul>
<p>이는 다음과 같은 tagged template이 문제가 된다는 것을 의미하는데, ECMAScript문법에 따라, parser는 유효한 유니 코드 탈출 시퀀스가 있는지 확인하지만 형식이 잘못되었기 때문에 오류가 발생합니다.</p>
<pre ><code>latex`\unicode`
// Throws in older ECMAScript versions (ES2016 and earlier)
// SyntaxError: malformed Unicode character escape sequence</code></pre>
<h4 id="ES2018_revision_of_illegal_escape_sequences">ES2018 revision of illegal escape sequences</h4>
<p>Tagged templates은 다른 escapes sequences가 일반적으로 사용되는 언어 (예 : <a href="https://en.wikipedia.org/wiki/Domain-specific_language">DSLs</a> 또는 <a href="https://en.wikipedia.org/wiki/LaTeX">LaTeX</a>)의 임베딩을 허용해야합니다. ECMAScript proposal <a href="https://tc39.github.io/proposal-template-literal-revision/">Template Literal Revision</a> (4 단계, ECMAScript 2018 표준에 통합됨)은 tagged templates에서 ECMAScript escape sequences의 구문 제한을 제거합니다.</p>
<p>그러나 illegal escape sequences는 여전히 "cooked"라고 표현되어야합니다. "cooked"배열의 {{jsxref ( "undefined")}} 요소로 나타납니다 :</p>
<pre ><code>function latex(str) {
return { "cooked": str[0], "raw": str.raw[0] }
}
latex`\unicode`
// { cooked: undefined, raw: "\\unicode" }</code></pre>
<p>escape sequence 제한은 <em>tagged</em> templates에만 적용되며 <em>untagged</em> template literals에는 적용되지 않습니다.</p>
<div class="warning">
<p>let bad = `bad escape sequence: \unicode`;</p>
</div>
<h2 id="Specifications">Specifications</h2>
<table>
<tbody>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
<tr>
<td>{{SpecName('ES2015', '#sec-template-literals', 'Template Literals')}}</td>
<td>{{Spec2('ES2015')}}</td>
<td>Initial definition. Defined in several section of the specification: <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-template-literals">Template Literals</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-tagged-templates">Tagged Templates</a></td>
</tr>
<tr>
<td>{{SpecName('ESDraft', '#sec-template-literals', 'Template Literals')}}</td>
<td>{{Spec2('ESDraft')}}</td>
<td>Defined in several section of the specification: <a href="https://tc39.github.io/ecma262/#sec-template-literals">Template Literals</a>, <a href="https://tc39.github.io/ecma262/#sec-tagged-templates">Tagged Templates</a></td>
</tr>
<tr>
<td><a href="https://tc39.github.io/proposal-template-literal-revision/">Template Literal Revision</a></td>
<td>Stage 4 draft</td>
<td>Drops escape sequence restriction from tagged templates</td>
</tr>
</tbody>
</table>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<p>{{Compat("javascript.grammar.template_literals")}}</p>
<h2 id="See_also">See also</h2>
<ul>
<li>{{jsxref("String")}}</li>
<li>{{jsxref("String.raw()")}}</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">Lexical grammar</a></li>
<li><a href="https://gist.github.com/WebReflection/8f227532143e63649804">Template-like strings in ES3 compatible syntax</a></li>
<li><a href="https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2/">"ES6 in Depth: Template strings" on hacks.mozilla.org</a></li>
</ul>
|