近期公司准备重构项目,语言翻译要求不能用映射表,后来发现了jquery国际化(jQuery.i18n.properties ),在前端实现
先简单的一下jQuery.i18n.properties
jQuery.i18n.properties是一款轻量级的jQuery国际化插件,能实现Web前端的国际化。
jQuery.i18n.properties是一款轻量级的jquery国际化插件,能实现Web前端的国际化,国际英文单词为:internationalization,又称i18n,“i"为单词的第一个字母,”18“为”i"和“n”之间的单词个数,而“n"表示单词的最后一个字母。jQuery.i18n.properties采用.properties文件对JavaScript进行国际化,jQuery.i18n.properties插件首先加载默认的资源文件(strings.properties ),然后加载针对特定的语言环境的资源文件(strings_zh.properties ),这节保证了在未提供语言某种语言的翻译时,默认值始终有效
具体看代码哈哈
第一步先看一下文件目录
第二步
- 下载必须的js文件
- jquery
- jquery.i18n.properties.js
第三步
新建静态页面
<html lang="en">
<head>
<meta charset="UTF-8">
<title class="i18n" name='title'></title>
<meta id="i18n_pagename" content="index-common">
<meta name="viewport" content="width=device-width">
<meta name="keywords" content="" />
<meta name="description" content=""/>
</head>
<body>
<div class="lan">
<div class="lan1"><label class="i18n" name="lan"></label></div>
<div class="lan2">
<select id="language">
<option value="zh-CN">中文简体</option>
<option value="zh-TW">中文繁體</option>
<option value="en">English</option>
</select>
</div>
</div>
<br>
<hr>
<div><label class="i18n" name="hellomsg1"></label><label class="i18n" name="hellomsg2"></label></div><br>
<div><label class="i18n" name="commonmsg1"></label><label class="i18n" name="commonmsg2"></label></div><br>
<div>
<input type="search" class="i18n-input" selectname="searchPlaceholder" selectattr="placeholder">
</div>
<script src="jquery-3.3.1.min.js"></script>
<!-- 加载语言包文件 -->
<script src="jquery.i18n.properties.js"></script>
<script src="language.js"></script>
</body>
</html>
说明
- meta id=”i18n_pagename” content=”index-common” 这里面的index-common写法,这里是引 入了两个资源文件index和common,这样做的好处就是,我们可以把公用部分的资源文件放到common里面,例如页头,页脚等,而且不需在每个页面都复制这部分内容,当共有内容有所变化,只需要修改common.properties就可以全部修改啦。
- 获取方式一:label class=”i18n” name=”hellomsg1”这里面class=”i18n”写法,下边在js里面我们可以根据类选择器获取需要国际化的地方,然后name=”hellomsg1”这里面的hellomsg1跟资源文件里面的key保持一致。获取方式二:input type=”search” class=”i18n-input” selectname=”searchPlaceholder” selectattr=”placeholder”这里面的class=”i18n-input”写法,跟上边的区别就是可以给html标签的任何属性可以赋值,例如placeholder,name,id什么的都可以,selectattr=”placeholder”里面的placeholder就是要赋值的属性,selectname=”searchPlaceholder”里面的searchPlaceholder跟资源文件里面的key保持一致。
第四步
配置language.js
/**
* cookie操作
*/
var getCookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
var path = options.path ? '; path=' + options.path : '';
var domain = options.domain ? '; domain=' + options.domain : '';
var s = [cookie, expires, path, domain, secure].join('');
var secure = options.secure ? '; secure' : '';
var c = [name, '=', encodeURIComponent(value)].join('');
var cookie = [c, expires, path, domain, secure].join('')
document.cookie = cookie;
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};
/**
* 获取浏览器语言类型
* @return {string} 浏览器国家语言
*/
var getNavLanguage = function(){
if(navigator.appName == "Netscape"){
var navLanguage = navigator.language;
return navLanguage.substr(0,2);
}
return false;
}
/**
* 设置语言类型: 默认为中文
*/
var i18nLanguage = "zh-CN";
/*
设置一下网站支持的语言种类
*/
var webLanguage = ['zh-CN', 'zh-TW', 'en'];
/**
* 执行页面i18n方法
* @return
*/
var execI18n = function(){
/*
获取一下资源文件名
*/
var optionEle = $("#i18n_pagename");
if (optionEle.length < 1) {
console.log("未找到页面名称元素,请在页面写入\n <meta id=\"i18n_pagename\" content=\"页面名(对应语言包的语言文件名)\">");
return false;
};
var sourceName = optionEle.attr('content');
sourceName = sourceName.split('-');
/*
首先获取用户浏览器设备之前选择过的语言类型
*/
if (getCookie("userLanguage")) {
i18nLanguage = getCookie("userLanguage");
} else {
// 获取浏览器语言
var navLanguage = getNavLanguage();
if (navLanguage) {
// 判断是否在网站支持语言数组里
var charSize = $.inArray(navLanguage, webLanguage);
if (charSize > -1) {
i18nLanguage = navLanguage;
// 存到缓存中
getCookie("userLanguage",navLanguage);
};
} else{
console.log("not navigator");
return false;
}
}
/* 需要引入 i18n 文件*/
if ($.i18n == undefined) {
console.log("请引入i18n js 文件")
return false;
};
/*
这里需要进行i18n的翻译
*/
jQuery.i18n.properties({
name : sourceName, //资源文件名称
path : i18nLanguage +'/', //资源文件路径
mode : 'map', //用Map的方式使用资源文件中的值
language : i18nLanguage,
callback : function() {//加载成功后设置显示内容
var insertEle = $(".i18n");
console.log(".i18n 写入中...");
insertEle.each(function() {
// 根据i18n元素的 name 获取内容写入
$(this).html($.i18n.prop($(this).attr('name')));
});
console.log("写入完毕");
console.log(".i18n-input 写入中...");
var insertInputEle = $(".i18n-input");
insertInputEle.each(function() {
var selectAttr = $(this).attr('selectattr');
if (!selectAttr) {
selectAttr = "value";
};
$(this).attr(selectAttr, $.i18n.prop($(this).attr('selectname')));
});
console.log("写入完毕");
}
});
}
/*页面执行加载执行*/
$(function(){
/*执行I18n翻译*/
execI18n();
/*将语言选择默认选中缓存中的值*/
$("#language option[value="+i18nLanguage+"]").attr("selected",true);
/* 选择语言 */
$("#language").on('change', function() {
var language = $(this).children('option:selected').val()
console.log(language);
getCookie("userLanguage",language,{
expires: 30,
path:'/'
});
location.reload();
});
});
path : i18nLanguage +’/’, //资源文件路径不要搞错啦
第五步
新建不同语言的资源文件
- zh-CN/index.properties
title=i18n资源国际化
lan=语言选择:
hellomsg1=首页消息:
hellomsg2=资源国际化!这是首页消息!
searchPlaceholder=请输入搜索信息
- zh-CN/common.properties
commonmsg1=通用消息:
commonmsg2=资源国际化!这是通用消息哦!
- zh-TW/index.properties
title=i18n資源國際化
lan=語言選擇:
hellomsg1=首頁消息:
hellomsg2=資源國際化! 这是首頁消息!
searchPlaceholder=請輸入搜索信息
- zh-TW/common.properties
commonmsg1=通用消息:
commonmsg2=資源國際化!這是通用消息哦!
- en/index.properties
title=i18n Resource Internationalization
lan=Language:
hellomsg1=Index message:
hellomsg2=Hello word! This is index message!
searchPlaceholder=Please input serach information
- en/common.properties
commonmsg1=Common message:
commonmsg2=This is common message!
注意
这里我没有按照jquery.i18n.properties上边那种strings.properties,strings_zh.properties写法写,我觉得把资源文件按语言类型文件夹划分,更直观些,故而将所有中文简体放在zh-CN下边,所有中文繁体放在zh-TW下边,英语放在en下边。会导致它每次都会去请求index_zh.properties,出现404请求错误,不过没啥大影响啦!
还有一点要注意,启动这个项目需要服务器的支持可以用node简单搭建一个,也可以用Apache,有一个不错的工具live-server用npm全局安装一下就好。就相当于一个服务器了,当然现在大部分编辑器都自带服务器想webstorm,vscode,hbuild等
看一下效果图