IT 성장일기
[Javascript] 템플릿 리터럴(Template literal) 응용하기 본문
반응형
템플릿 리터럴(Template literal) 응용하기
지난 번에 ES6 템플릿 리터럴 문법의 간단한 사용법을 공부했습니다.
이어서 오늘은 조금 더 실무나 프로젝트에서 활용 가능한 응용 방법을 조금 알아봤습니다.
HTML 빌더
데이터를 매개변수로 받아서 동적으로 HTML요소를 생성하고 반환하는 함수를 만들어볼 수 있습니다.
버튼도 만들고 리스트도 만들고 테이블도 만들 수 있습니다.
const buttons = ['Home', 'About', 'Contact'];
const buttonHTML = buttons.map(btn => `<button>${btn}</button>`).join('');
document.body.innerHTML += `<div>${buttonHTML}</div>`;
const items = ['Item 1', 'Item 2', 'Item 3'];
const listHTML = `
<ul>
${items.map(item => `<li>${item}</li>`).join('')}
</ul>
`;
document.body.innerHTML += listHTML;
const categories = [
{ name: 'Fruits', items: ['Apple', 'Banana', 'Orange'] },
{ name: 'Vegetables', items: ['Carrot', 'Broccoli', 'Spinach'] },
{ name: 'Dairy', items: ['Milk', 'Cheese', 'Butter'] }
];
const nestedListHTML = `
<ul>
${categories.map(category => `
<li>
<strong>${category.name}</strong>
<ul>
${category.items.map(item => `<li>${item}</li>`).join('')}
</ul>
</li>
`).join('')}
</ul>
`;
document.body.innerHTML += nestedListHTML;
function createTable(data) {
return `
<table border="1">
<thead>
<tr>${Object.keys(data[0]).map(key => `<th>${key}</th>`).join('')}</tr>
</thead>
<tbody>
${data.map(row => `
<tr>${Object.values(row).map(value => `<td>${value}</td>`).join('')}</tr>
`).join('')}
</tbody>
</table>
`;
}
const fruits = [
{ Name: 'Apple', Color: 'Red', Price: 20 },
{ Name: 'Banana', Color: 'Yellow', Price: 15 },
{ Name: 'Melon', Color: 'Green', Price: 30 }
];
document.body.innerHTML = createTable(fruits);
CSS 빌더
요소와 스타일을 매개변수로 넘겨서 동적으로 스타일을 생성할 수도 있습니다.
단순히 특정 요소에 어떤 스타일을 적용하는 것과는 조금 다릅니다.
스타일시트 자체를 생성해주는 함수를 만들 수 있습니다.
function createCSS(styles) {
return `
<style>
${Object.entries(styles).map(([selector, rules]) => `
${selector} {
${Object.entries(rules).map(([property, value]) => `${property}: ${value};`).join(' ')}
}
`).join('')}
</style>
`;
}
let styles = {
body: { 'background-color': '#f0f0f0', color: '#333' },
h1: { 'font-size': '2em', 'text-align': 'center' },
'.container': { margin: '0 auto', width: '80%' }
};
document.head.innerHTML += createCSS(styles);
function applyTheme(theme) {
const themeCSS = `
body {
background-color: ${theme.background};
color: ${theme.text};
}
button {
background-color: ${theme.buttonBackground};
color: ${theme.buttonText};
border: none;
padding: 10px 20px;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
`;
const styleTag = document.getElementById('dynamic-theme') || document.createElement('style');
styleTag.id = 'dynamic-theme';
styleTag.textContent = themeCSS;
document.head.appendChild(styleTag);
}
const darkTheme = {
background: '#333',
text: '#fff',
buttonBackground: '#007BFF',
buttonText: '#fff',
};
const lightTheme = {
background: '#fff',
text: '#333',
buttonBackground: '#f0f0f0',
buttonText: '#333',
};
// 기본 테마 적용
applyTheme(lightTheme);
// 다크 테마로 전환하는 버튼
document.body.innerHTML += '<button onclick="applyTheme(darkTheme)">Switch to Dark Theme</button>';
함수 생성기
함수명, 바디, 매개변수를 매개변수로 받아 함수 제너레이터를 만들 수 있습니다.
보안상 문제가 발생할 수 있고 활용도가 높지 않아서 이런게 있구나 정도로만 알고 넘어가겠습니다.
function generateFunction(name, args, body) {
return `
function ${name}(${args.join(', ')}) {
${body}
}
`;
}
const funcCode = generateFunction('addNumbers', ['a', 'b'], 'return a + b;');
console.log(funcCode);
일을 하면서 사용하다보니 너무나 편리하고 유용해서 여러가지 사용법을 더 찾아보게 되었습니다.
하지만 극한으로 활용하기보다는 보편적이고 라이트하게 사용법을 익혀놓으면 더 좋을 것 같습니다.
감사합니다!
반응형
'Script > Javascript' 카테고리의 다른 글
[Javascript] 매핑 객체 패턴으로 분기문 깔끔하게 사용하기 (Mapping Object Pattern) (0) | 2024.12.24 |
---|---|
[Javascript] Set, map, filter로 배열의 차집합 구하기 (0) | 2024.12.13 |
[Javascript] 템플릿 리터럴(Template literal) 사용하기 (0) | 2024.11.30 |
[Javascript] replace 함수 3차원으로 활용하기(feat. 정규식) (3) | 2024.11.14 |
[Javascript] 정규식으로 이름과 휴대전화번호 유효성 검증하기 (4) | 2024.10.30 |