Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tagged Template Literals trong JavaScript


Template literals cho phép tạo tagged template literals. Tagged literal giống như định nghĩa hàm, cho phép parse template literal. Hàm tag nhận mảng các chuỗi tĩnh làm đối số đầu, các giá trị interpolated làm các đối số tiếp theo.

Ví dụ

<!DOCTYPE html> <html lang="vi"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Tagged template</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; color: blueviolet; } </style> </head> <body> <h1>Tagged Template Literals trong JavaScript</h1> <div class="result"></div> <br /> <button class="Btn">NHẤN VÀO ĐÂY</button> <h3>Nhấn nút để truyền template string qua tagged literal cho hàm sampleTag()</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); function sampleTag(strings, name, age, rollNo) { let section; if (rollNo > 50) { section = "A"; } else { section = "B"; } return `${name} roll no: ${rollNo} age :${age} is in section ${section}`; } let name = "Rohan", age = 16, rollNo = 22; BtnEle.addEventListener("click", () => { resEle.innerHTML = sampleTag`${name} aged ${age} and roll no ${rollNo} is new in the school`; }); </script> </body> </html>

Kết quả

Khi nhấn nút: Rohan roll no: 22 age :16 is in section B

Hàm tag sampleTag nhận strings = [" aged ", " and roll no ", " is new in the school"], và các giá trị interpolated name, age, rollNo. Dùng cho: sanitization (prevent XSS), i18n, SQL query builder (sql`...`), styled-components (CSS-in-JS).