템플릿 리터럴을 사용하면 태그가 지정된 템플릿 리터럴을 만들 수도 있습니다. 태그가 지정된 리터럴은 함수 정의와 같으며 템플릿 리터럴을 구문 분석할 수 있습니다. 태그가 지정된 리터럴은 괄호를 포함하지 않으며 태그 함수는 문자열 값의 배열을 첫 번째 인수로 가져옵니다. 그런 다음 나머지 인수는 다른 관련 매개변수로 전달됩니다.
다음은 JavaScript에서 태그가 지정된 템플릿 리터럴을 구현하는 코드입니다 -
예시
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</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 in JavaScript</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to pass the template string using tagged template literal to sampleTag() function</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> 출력

'여기를 클릭' 버튼을 클릭하면 -
