黑白梦

使用 lodash 的 template 方法自定义模板规则

lodash 的 template 用于创建一个编译的模板函数,允许我们利用正则定义任意模板规则,比如实现类似于 vue-i18n 的 t 方法。

默认模板规则:

var compiled = _.template('hello <%= user %>!');
compiled({ 'user': 'fred' });

通过 interpolate 定义分隔符,比如定义 vue-i18n 的模式,通过 {} 包裹变量。

const str = 'aaa{num}'
const compiled = _.template(str, {
    interpolate: /{([\s\S]+?)}/g,
});
compiled({ num: 1 });

可以进一步封装一个 t 函数,实现类似于 vue-i18n 的方法:

const map = {
    a: {
        b: {
            c: 'aaa{num}'
        }
    }
}

function t(key, values) {
    const compiled = _.template(_.get(map, key), {
        interpolate: /{([\s\S]+?)}/g,
    });
    return compiled(values);
}

console.log(t('a.b.c', {num: 1}));

在此基础上,结合全局状态存储当前语言,判断需要展示的 map ,封装一个 hook ,就可以在 react 中自行实现 i18n 功能,并快速把 vue-i18n 的国际化文件直接搬过来。