ES6 開始 JavaScript 也有和其他程式語言一樣的 template 功能。以前組成字串要用 + 號來結合變數和字串,還會擔心單引號和雙引號的問題。有了 template 功能,用 backtick (esc 下面那個鍵)將字串包起來,變數部分用 ${變數名},裡面還可以使用運算式,或者函式。
const name = 'Snickers';
const age = 2;
const sentence = `My dog ${name} is ${age * 7} years old.`;
// sentence: "My dog Snickers is 14 years old.
也適用在 multi-line strings。
const person = {
name: ‘Yow-Long’,
job: ‘Web Developer’,
city: ‘Taipei’,
bio: ‘Yow-Long loves to teach web development!’,
};
// 用 backtick 把 HTML template 包住
// 變數符號會代入指定的變數名稱
const markup = `
<div class=“person”>
<h2>
${person.name}
<span class=“job”>${person.job}</span>
</h2>
<p class=“location”>${person.city}</p>
<p class=“bio”>${person.bio}</p>
</div>
`;
Template strings 也支援巢狀堆疊的使用方法。
const movies = [
{ name: 'Toy Story', year: 1995 },
{ name: 'Finding Nemo', year: 2003 },
{ name: 'WALL-E', year: 2008 }
];
const markup = `
<ul class="movies">
${movies.map(movie => `
<li>
${movie.name}
was released in
${movies.year}
</li>`).join('')}
</ul>
`;