エンタメ特化型、心を動かすWeb制作。
まずは無料で相談いたします!
企業サイトやブランドサイトでは、日本語と英語の2言語対応を求められるケースが増えています。
しかし、「どのURLに英語版ファイルが存在するのか」「階層によってファイル名をどう切り替えるのか」など、単純に見えて意外とロジックが複雑になりがちです。
今回は、実際のプロジェクトで使用した JavaScriptによる言語切り替えロジックを紹介しながら、実装のポイントと考え方を整理していきます。
フルスタックサイト構築
このコードは、以下の要件を満たすために組まれています。
CMSなしの静的サイトの場合、英語版のファイル名がパスによって違うこともしばしばあります。
例:
トップページ:index.php → index_en.php
下層ページ:index.php → en.php
つまり、「フォルダの深さでルールが変わる」仕様。
これを自動判定し、ユーザーにとって自然な切り替えを実現しています。
/* ランゲージボタン */
document.addEventListener('DOMContentLoaded', () => {
const langBtn = document.getElementById('lang-switch');
if (!langBtn) return;
const langLi = langBtn.closest('.lang');
const currentPath = window.location.pathname;
let targetPath = '';
let isEnglish = false;
console.log("現在のパス:", currentPath);
// 英語ページなら日本語に戻す
if (currentPath.endsWith('index_en.php')) {
targetPath = currentPath.replace('index_en.php', 'index.php');
langBtn.textContent = 'JP';
isEnglish = true;
} else if (currentPath.endsWith('en.php')) {
targetPath = currentPath.replace('en.php', 'index.php');
langBtn.textContent = 'JP';
isEnglish = true;
}
// 日本語ページなら英語へ切り替え
else if (currentPath.endsWith('index.php')) {
const depth = currentPath.split('/').filter(Boolean).length;
if (depth <= 2) {
targetPath = currentPath.replace('index.php', 'index_en.php');
} else {
targetPath = currentPath.replace('index.php', 'en.php');
}
langBtn.textContent = 'EN';
}
// ディレクトリアクセス(例: /company/)
else if (currentPath.endsWith('/')) {
const depth = currentPath.split('/').filter(Boolean).length;
if (depth <= 1) {
targetPath = currentPath + 'index_en.php';
} else {
targetPath = currentPath + 'en.php';
}
langBtn.textContent = 'EN';
}
// 想定外パターン
else {
targetPath = currentPath.replace('.php', '_en.php');
langBtn.textContent = 'EN';
}
// ファイル存在チェック(なければボタン非表示)
fetch(targetPath, { method: 'HEAD' })
.then(response => {
if (response.ok) {
langLi.style.display = 'flex';
langBtn.addEventListener('click', (e) => {
e.preventDefault();
window.location.href = targetPath;
});
} else {
langLi.style.display = 'none';
}
})
.catch(() => {
langLi.style.display = 'none';
});
});
const depth = currentPath.split('/').filter(Boolean).length;
/company/ → depth=1
/service/web/ → depth=2
/service/web/project/ → depth=3
トップか下層かで「英語版ファイル名」が変わる仕様に対応しています。
fetch(targetPath, { method: 'HEAD' })
HEAD リクエストで存在チェックし、
あれば → ボタン表示
なければ → ボタン非表示
クライアントに「英語版が無いのにENボタンがある」誤解を与えません。
_en.php を自動生成targetPath = currentPath.replace('.php', '_en.php');
規則外でも最低限の英語版遷移を作る保険です。
静的HTML + PHPで構成された企業サイト
CMSなしでページごとに英語ファイルを持っている構成
URL構造が一定ではないサイト
英語版が存在しないページも混在しているサイト
ProcessWireやWordPressなどCMS利用の場合はより効率よい方法がありますが、静的サイトでの多言語切替としては十分に堅牢な構成です。
今回の実装の考え方を応用すると、以下のような改善も可能です。
● 切替後に「同じコンテンツの英語版」に飛ばす
→ CMSならページIDで紐づけられる
● 言語パラメータ(?lang=en)方式に変更
→ SPAやReact構成と相性が良い
● サイト全体で統一したファイル命名規則を導入
→ 運用コスト大幅削減
Webサイト制作についてご相談がある方は、お問い合わせフォームよりお気軽にご連絡ください。