From 898b52edcb47bcb3e9d6106e74ca73e74ea01e70 Mon Sep 17 00:00:00 2001 From: sillylaird Date: Thu, 3 Sep 2026 00:33:59 +0000 Subject: import live www.sillylaird.ca webroot --- partials/i18n.php | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 partials/i18n.php (limited to 'partials/i18n.php') 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 @@ + 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; + } +} -- cgit v1.2.3