最近,新的VUE項目還沒有開發完成,原來的老項目又提出了新的需求:國際化 (多語言切換)。在實現的過程中,有很多值得注意和分享的東西,在此寫一個demo,希望對大家有幫助!
實現效果 !
demo 目錄結構
一, 創建html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title class="i18n" name='title'></title> <meta id="i18n_pagename" content="index-common"> <title>i18n</title> </head> <body> <select id="language"> <option value="zh-CN">中文簡體</option> <option value="en">English</option> </select> <div> <h5 class="i18n" name="signOut"></h5> <h5 class="i18n" name="searchPlaceholder"></h5> <h5 class="i18n" name="station"></h5> <h5 class="i18n" name="partno"></h5> <h5 class="i18n" name="partno"></h5> <h5 class="i18n" name="description"></h5> <h5 class="i18n" name="query"></h5> <h5 class="i18n" name="pleaseSelect"></h> <h5 class="i18n" name="add"></h5> <h5 class="i18n" name="edit"></h5> <h5 class="i18n" name="delete"></h5> </div> </body> </html> <script src="js/jquery.js"></script> <script src="js/jquery.i18n.properties-min-1.0.9.js"></script> <script src="js/language.extensions.js"></script> <style> h{ color: red; font-size:20px; } </style>
二, 創建i18n目錄
在i18n目錄下的en和zh-CN各創建一個 common.properties文件 (i18n/en/common.properties i18n/zh-CN/common.properties)
三, i18n/en/common.properties
searchPlaceholder=Please input serach information signOut=Login Out station=Station partno=Part No description=Description query=Query pleaseSelect=Please Select add=Add edit=Edit delete=Delete
四, i18n/zh-CN/common.properties
searchPlaceholder=請輸入關鍵字 signOut=退出 station=站點 partno=零件號 description=描述 query=查詢 pleaseSelect=請選擇 add=新增 edit=編輯 delete=刪除
五, 在js文件創建 language.extensions.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({…})這里面就是給頁面需要國際化的地方賦值。
做到這里 貌似大功告成!當你直接在google瀏覽器里面運行的時候你會發現一個跨域的問題。
要求你在一種webServer里面去訪問.properties文件,這個問題你只需要使用任何一種webserver運行即可,Apache、Node的web服務器等。