eatkano现用多语言方案(i18n)

咕了那么久终于有人做多语言了

语言文件

大概长这样。也就是文本抽出来放json,再由各自语言替换到原位置

均以浏览器的Accept-Language自动选择对应语言文件,非常方便

h5中使用

I18N作用代码(js)

    const DEFAULT_I18N_RESOURCE = 'en';

    function getJsonI18N() {
        let res;
        let lang = navigator.language.substring(0, 2);

        function ajax(name, error) {
            $.ajax({
                url: `./static/i18n/${name}.json`,
                dataType: 'json',
                method: 'GET',
                async: false,
                success: data => res = data,
                error: error
            });
        }

        ajax(lang, () => {
            ajax(DEFAULT_I18N_RESOURCE, () => {});
        })

        return res;
    }

    const I18N = getJsonI18N()

    $('[data-i18n]').each(function() {
        const content = I18N[this.dataset.i18n];
        $(this).text(content);
    });

    $('[data-placeholder-i18n]').each(function() {
        $(this).attr('placeholder', I18N[this.dataset.placeholderI18n]);
    });

    $('html').attr('lang', I18N['lang']);

js中使用其中文本

I18N['index']

html中使用其中文本

data-i18n="index"
<!-- 示例 -->
<title data-i18n="eat-kano"></title>

PHP中使用

I18N作用代码(php)

$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
// non-existent default en
$lang_file = file_exists('static/i18n/' . $lang . '.json') ? "static/i18n/" . $lang . ".json" : "static/i18n/en.json";
$lang_data = file_get_contents($lang_file);
$i18n = json_decode($lang_data, true);

php中使用

$i18n['index'];
// 示例:
<title><?php echo $i18n['rank-title']; ?></title>

点赞
  1. ID.说道:
    QQbrowser Windows 7
    有人吗?
  2. 123456说道:
    Google Chrome Android 10
    无聊
  3. bhhh说道:
    MIUI Browser Android 12
    111
  4. 阿乐说道:
    Firefox Windows 10
    数据库连接失败咋办啊 up

回复 bhhh 取消回复

邮箱不会被公开,用于显示Gravatar的头像