diff options
| author | sillylaird <sillyfanboy@gmail.com> | 2026-09-03 00:33:59 +0000 |
|---|---|---|
| committer | sillylaird <sillyfanboy@gmail.com> | 2026-09-03 00:33:59 +0000 |
| commit | 898b52edcb47bcb3e9d6106e74ca73e74ea01e70 (patch) | |
| tree | 85c6ee5ad58b860144551184d4cf86b560c62b91 /partials/i18n.php | |
| download | www-898b52edcb47bcb3e9d6106e74ca73e74ea01e70.tar.gz www-898b52edcb47bcb3e9d6106e74ca73e74ea01e70.zip | |
Diffstat (limited to '')
| -rw-r--r-- | partials/i18n.php | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/partials/i18n.php b/partials/i18n.php new file mode 100644 index 0000000..6f76419 --- /dev/null +++ b/partials/i18n.php @@ -0,0 +1,40 @@ +<?php +// Minimal i18n helper. Detects language from the current filename suffix +// (_jp.php / _zh.php) so it matches the existing URL scheme, and loads a +// flat key -> string dict from locales/{code}.php. +// +// Usage in a page: +// require_once __DIR__ . '/../partials/i18n.php'; // adjust relative path +// echo t('home.title'); +// +// Missing keys fall back to the English dict, then to the key itself. + +if (!function_exists('t')) { + function _i18n_lang(): string { + // Prefer SCRIPT_NAME: under nginx + php-fpm, PHP_SELF is often empty. + $f = basename((string)($_SERVER['SCRIPT_NAME'] ?? $_SERVER['PHP_SELF'] ?? 'index.php')); + if ($f === '') $f = 'index.php'; + if (str_ends_with($f, '_zh.php')) return 'zh'; + if (str_ends_with($f, '_jp.php')) return 'ja'; + return 'en'; + } + + function _i18n_load(string $code): array { + static $cache = []; + if (isset($cache[$code])) return $cache[$code]; + $path = __DIR__ . '/../locales/' . $code . '.php'; + $cache[$code] = is_file($path) ? (array)include $path : []; + return $cache[$code]; + } + + function t(string $key, ?string $lang = null): string { + $lang = $lang ?? _i18n_lang(); + $dict = _i18n_load($lang); + if (array_key_exists($key, $dict)) return $dict[$key]; + if ($lang !== 'en') { + $en = _i18n_load('en'); + if (array_key_exists($key, $en)) return $en[$key]; + } + return $key; + } +} |
