テンプレートリテラル応用ライブラリ(自作ヘルパー)
これは、テンプレートリテラルのタグ付きテンプレート関数を活用して、「HTML整形」「翻訳」「スタイル生成」などを自動で処理できる便利ツール集を自作する形です。
目標
テンプレートリテラルのタグ機能を使って:
- ✅ HTML整形+自動エスケープ
- ✅ 翻訳(多言語対応)
- ✅ CSSスタイル生成(CSS-in-JS風)
- ✅ デバッグ/ロギング
を行う、軽量ユーティリティライブラリを作る。
構成イメージ
// helpers.js
export const html = ...
export const i18n = ...
export const css = ...
export const debug = ...
JavaScript実装例(最小構成)
1. HTMLタグテンプレート(自動サニタイズつき)
// HTMLエスケープ用
function escapeHTML(str) {
return String(str).replace(/[&<>'"]/g, c => ({
'&':'&', '<':'<', '>':'>', "'":''', '"':'"'
}[c]));
}
// タグ付きテンプレート
export function html(strings, ...values) {
return strings.reduce(
(out, str, i) => out + str + (values[i] !== undefined ? escapeHTML(values[i]) : ""),
""
);
}
// --- 使用例 ---
const user = "<script>alert('XSS')</script>";
const safeHTML = html`<p>こんにちは、${user}さん!</p>`;
console.log(safeHTML);
// → <p>こんにちは、<script>alert('XSS')</script>さん!</p>
JavaScript📘 ポイント:ユーザー入力を自動で安全化してHTML整形。
2. i18n(多言語翻訳テンプレート)
// 翻訳辞書
const dict = {
ja: { hello: "こんにちは", apple: "りんご" },
en: { hello: "Hello", apple: "apple" }
};
export function i18n(lang = "ja") {
return (strings, ...values) => {
return strings.reduce(
(out, str, i) => out + str + (values[i] ? dict[lang][values[i]] ?? values[i] : ""),
""
);
};
}
// --- 使用例 ---
const t = i18n("en");
console.log(t`${"hello"} ${"apple"}!`); // → Hello apple!
JavaScript📘 ポイント:辞書を切り替えるだけで多言語対応可能。
3. CSSテンプレート(CSS-in-JS風)
export function css(strings, ...values) {
const style = strings.reduce(
(out, str, i) => out + str + (values[i] ?? ""),
""
);
const className = "c" + Math.random().toString(36).slice(2, 7);
const sheet = document.createElement("style");
sheet.textContent = `.${className}{${style}}`;
document.head.appendChild(sheet);
return className;
}
// --- 使用例 ---
const btnClass = css`
background: blue;
color: white;
padding: 10px;
border-radius: 5px;
`;
document.body.innerHTML = `<button class="${btnClass}">Click!</button>`;
JavaScript📘 ポイント:テンプレート内でスタイルを記述 → 自動で <style> に反映。
4. debug(ロギングテンプレート)
export function debug(strings, ...values) {
const msg = strings.reduce((out, str, i) => out + str + (values[i] ?? ""), "");
console.log(`🪶 [DEBUG]: ${msg}`);
return msg;
}
// --- 使用例 ---
const val = 42;
debug`現在の値: ${val}`;
// → 🪶 [DEBUG]: 現在の値: 42
JavaScript総合利用例
import { html, i18n, css, debug } from "./helpers.js";
const t = i18n("ja");
const box = css`
background: #f0f0f0;
padding: 10px;
border: 1px solid #ccc;
`;
const message = html`<div class="${box}">${t`${"hello"}`}!</div>`;
debug`生成されたHTML: ${message}`;
document.body.innerHTML = message;
JavaScript発展アイデア
- 🌍 i18nタグを外部JSON辞書と連携
- 🎨 cssタグに変数埋め込み(テーマカラー対応)
- 🔒 htmlタグを「サニタイズ強化モード」で使う
- 🧠 debugタグに時間・行番号を自動付与


