您的位置:首页 > Web前端 > JQuery

基于jQuery.i18n.properties 实现前端页面的资源国际化

2015-10-22 17:58 851 查看
之前web项目一直都是中文为主的,现在随着业务的需求,需要将网站语言支持多语言,这个着实给不管是前台还是后台都增加了不小的挑战,因为之前做的时候根本没有考虑多语言的问题,导致很多页面写的不是很灵活,样式写的比较死,中文看起来不错,其他语言又比较难看,其他语言看起来不错,中文比较难看,总之调了很久才能好。。。 哈哈哈,先吐槽一番。

今天,主要弄一下基于jQuery.i18n.properties 实现前端页面的资源国际化这个问题,也就是将页面中的显示中文的地方都变成可以根据用户选择的语言来变化的。网上也有很多js专门做这个国际化的,最终我们选择了jQuery.i18n.properties来实现。

先来copy一段关于jQuery.i18n.properties 的说明哈。

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),这就保证了在未提供某种语言的翻译时,默认值始终有效。

废话少说,直接上代码吧(just demo)!

第一步:

下载必须的js文件

jquery.i18n.properties.js

jquery.js

第二步:

新建demo静态页面index.html

<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=""/>
<link rel="stylesheet" href="css/index.css">
</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="js/jquery.js"></script>
<!-- 加载语言包文件 -->
<script src="js/jquery.i18n.properties-min-1.0.9.js"></script>
<script src="js/language.js"></script>
</body>
</html>


说明:

1、meta id=”i18n_pagename” content=”index-common” 这里面的index-common写法,这里是引 入了两个资源文件index和common,这样做的好处就是,我们可以把公用部分的资源文件放到common里面,例如页头,页脚等,而且不需在每个页面都复制这部分内容,当共有内容有所变化,只需要修改common.properties就可以全部修改啦。

2、获取方式一: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 : 'i18n/' + 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();
});
});


说明: 这个js文件写的比较详细有注释,大家一看应该就能懂,大致的就是第一次进来时,会根据浏览器的语言选择默认语言,然后用户每次选择不同的语言,会将选择的语言存入cookie,下一次进入取cookie里面的语言,核心i18n代码在 jQuery.i18n.properties({…})这里面就是给页面需要国际化的地方赋值。

第四步:

新建不用语言的资源文件index.properties,common.properties

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请求错误,不过没啥大影响啦!

大功告成!

来几张截图,看下效果如何!(页面有点丑呵,不影响啦!)

中文简体



中文繁体



英语

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: