生活随笔
收集整理的這篇文章主要介紹了
标签模板
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
標(biāo)簽?zāi)0?/h2>
模板字符串的功能,不僅僅是上面這些。它可以緊跟在一個函數(shù)名后面,該函數(shù)將被調(diào)用來處理這個模板字符串。這被稱為“標(biāo)簽?zāi)0濉惫δ?#xff08;tagged template)。
alert`123`// 等同于alert(123)
標(biāo)簽?zāi)0迤鋵嵅皇悄0?#xff0c;而是函數(shù)調(diào)用的一種特殊形式。“標(biāo)簽”指的就是函數(shù),緊跟在后面的模板字符串就是它的參數(shù)。
但是,如果模板字符里面有變量,就不是簡單的調(diào)用了,而是會將模板字符串先處理成多個參數(shù),再調(diào)用函數(shù)。
let a = 5;let b = 10;tag`Hello ${ a + b } world ${ a * b }`;// 等同于tag(['Hello ', ' world ', ''], 15, 50);
上面代碼中,模板字符串前面有一個標(biāo)識名tag,它是一個函數(shù)。整個表達(dá)式的返回值,就是tag函數(shù)處理模板字符串后的返回值。
函數(shù)tag依次會接收到多個參數(shù)。
function tag(stringArr, value1, value2){ // ...}// 等同于function tag(stringArr, ...values){ // ...}
tag函數(shù)的第一個參數(shù)是一個數(shù)組,該數(shù)組的成員是模板字符串中那些沒有變量替換的部分,也就是說,變量替換只發(fā)生在數(shù)組的第一個成員與第二個成員之間、第二個成員與第三個成員之間,以此類推。
tag函數(shù)的其他參數(shù),都是模板字符串各個變量被替換后的值。由于本例中,模板字符串含有兩個變量,因此tag會接受到value1和value2兩個參數(shù)。
tag函數(shù)所有參數(shù)的實際值如下。
- 第一個參數(shù):['Hello ', ' world ', '']
- 第二個參數(shù): 15
- 第三個參數(shù):50
也就是說,tag函數(shù)實際上以下面的形式調(diào)用。
tag(['Hello ', ' world ', ''], 15, 50)
我們可以按照需要編寫tag函數(shù)的代碼。下面是tag函數(shù)的一種寫法,以及運(yùn)行結(jié)果。
let a = 5;let b = 10;function tag(s, v1, v2) { console.log(s[0]); console.log(s[1]); console.log(s[2]); console.log(v1); console.log(v2); return "OK";}tag`Hello ${ a + b } world ${ a * b}`;// "Hello "// " world "// ""// 15// 50// "OK"
下面是一個更復(fù)雜的例子。
let total = 30;let msg = passthru`The total is ${total} (${total*1.05} with tax)`;function passthru(literals) { let result = ''; let i = 0; while (i < literals.length) { result += literals[i++]; if (i < arguments.length) { result += arguments[i]; } } return result;}msg // "The total is 30 (31.5 with tax)"
上面這個例子展示了,如何將各個參數(shù)按照原來的位置拼合回去。
passthru函數(shù)采用 rest 參數(shù)的寫法如下。
function passthru(literals, ...values) { let output = ""; let index; for (index = 0; index < values.length; index++) { output += literals[index] + values[index]; } output += literals[index] return output;}
“標(biāo)簽?zāi)0濉钡囊粋€重要應(yīng)用,就是過濾 HTML 字符串,防止用戶輸入惡意內(nèi)容。
let message = SaferHTML`<p>${sender} has sent you a message.</p>`;function SaferHTML(templateData) { let s = templateData[0]; for (let i = 1; i < arguments.length; i++) { let arg = String(arguments[i]); // Escape special characters in the substitution. s += arg.replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">"); // Don't escape special characters in the template. s += templateData[i]; } return s;}
上面代碼中,sender變量往往是用戶提供的,經(jīng)過SaferHTML函數(shù)處理,里面的特殊字符都會被轉(zhuǎn)義。
let sender = '<script>alert("abc")</script>'; // 惡意代碼let message = SaferHTML`<p>${sender} has sent you a message.</p>`;message// <p><script>alert("abc")</script> has sent you a message.</p>
標(biāo)簽?zāi)0宓牧硪粋€應(yīng)用,就是多語言轉(zhuǎn)換(國際化處理)。
i18n`Welcome to ${siteName}, you are visitor number ${visitorNumber}!`// "歡迎訪問xxx,您是第xxxx位訪問者!"
模板字符串本身并不能取代 Mustache 之類的模板庫,因為沒有條件判斷和循環(huán)處理功能,但是通過標(biāo)簽函數(shù),你可以自己添加這些功能。
// 下面的hashTemplate函數(shù)// 是一個自定義的模板處理函數(shù)let libraryHtml = hashTemplate` <ul> #for book in ${myBooks} <li><i>#{book.title}</i> by #{book.author}</li> #end </ul>`;
除此之外,你甚至可以使用標(biāo)簽?zāi)0?#xff0c;在 JavaScript 語言之中嵌入其他語言。
jsx` <div> <input ref='input' onChange='${this.handleChange}' defaultValue='${this.state.value}' /> ${this.state.value} </div>`
上面的代碼通過jsx函數(shù),將一個 DOM 字符串轉(zhuǎn)為 React 對象。你可以在 Github 找到j(luò)sx函數(shù)的具體實現(xiàn)。
下面則是一個假想的例子,通過java函數(shù),在 JavaScript 代碼之中運(yùn)行 Java 代碼。
java`class HelloWorldApp { public static void main(String[] args) { System.out.println(“Hello World!”); // Display the string. }}`HelloWorldApp.main();
模板處理函數(shù)的第一個參數(shù)(模板字符串?dāng)?shù)組),還有一個raw屬性。
console.log`123`// ["123", raw: Array[1]]
上面代碼中,console.log接受的參數(shù),實際上是一個數(shù)組。該數(shù)組有一個raw屬性,保存的是轉(zhuǎn)義后的原字符串。
請看下面的例子。
tag`First line\nSecond line`function tag(strings) { console.log(strings.raw[0]); // strings.raw[0] 為 "First line\\nSecond line" // 打印輸出 "First line\nSecond line"}
上面代碼中,tag函數(shù)的第一個參數(shù)strings,有一個raw屬性,也指向一個數(shù)組。該數(shù)組的成員與strings數(shù)組完全一致。比如,strings數(shù)組是["First line\nSecond line"],那么strings.raw數(shù)組就是["First line\\nSecond line"]。兩者唯一的區(qū)別,就是字符串里面的斜杠都被轉(zhuǎn)義了。比如,strings.raw 數(shù)組會將\n視為\\和n兩個字符,而不是換行符。這是為了方便取得轉(zhuǎn)義之前的原始模板而設(shè)計的。
總結(jié)
以上是生活随笔為你收集整理的标签模板的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。