자바스크립트에서 문자열을 다룰 때 Template Literals 를 사용해 본적이 있을 것이다. Template Listerals 는 ECMAScipt 2015 부터 나온 새로운 기능으로 백틱을 사용해서 문자열을 표현하는 것이다.
이 Template Literals 를 이용하면 이전에는 문자열에 변수 값을 표현하기 위해 더하기 연산자를 이용해 문자열을 합쳤던 것을 더하기 연산자를 사용하지 않고 손쉽게 표현할 수 있게 되었다.
const hello = "Hello World";
// ECMAScript 2015 이전
console.log("Welcome" + hello);
// ECMAScript 2015 이후
console.log(`Welcome ${hello}`);
위와 같은 Template Literal 은 대부분의 개발자들은 사용해보았을 것이다.
하지만 태그가 붙어있는 템플릿 리터럴은 거의 사용해보지 않았을 것이다. 단, Styled-components를 사용해 봤다면 본인도 모르는 사이 사용해 보았을 것이다.
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
Tagged Template Literals 는 Template Literal 를 이용해여 함수의 인자를 파싱하여 넘겨주는 것이다. 아래의 코드를 한번 확인해보자
const meal = 'dinner';
const taste = 'good';
function getSnackTaste(string, eat, flavor) {
let snack = 'cookie';
let feel = 'bad';
if (eat === 'breakfast') {
snack = 'milk'
}
if (flavor === 'bad') {
feel = 'good';
}
return string[0] + snack + string[1] + feel + '~~';
}
getSnackTaste`Today, ${meal} is ${taste}`; // Today, cookie is bad~~
위의 코드에서 함수 getSnackTaste의 input Parameters 를 확인해보면 아래와 같다는 것이다
["Today, ", " is ", ""] "dinner" "good"
또 다른 예제는 아래와 같다.
const food1 = '피자';
const food2 = '치킨';
const foodMsg = (texts, ...values) => {
console.log(texts);
console.log(values);
};
foodMsg`제가 어제 먹은 음식은 ${food1}그리고 ${food2}입니다.`;
// [ '제가 어제 먹은 음식은 ', '그리고 ', '입니다.' ]
// [ '피자', '치킨' ]
결론은 input parameters를 틱택을 이용해서 넘겨줄 수 있다는 뜻이다.
과연 tagged template literal의 경우는 얼마나 사용할지 미지수이다.
오히려 동료들과 소통에 문제가 발생 할 수 있기 때문에 덜 사용하지 싶다.