man*_*eus 9 internationalization mustache
我有一些静态的html文件,并希望通过mustache.js更改客户端修改内部的静态文本.
似乎这可能是Twitter在github上的小胡子扩展:https://github.com/bcherry/mustache.js
但最近特定的I18n扩展已被删除或更改.
我想象一个解决方案,其中http:/server/static.html?lang=en加载mustache.js和基于lang参数的语言JSON文件data_en.json.
然后小胡子替换{{tags}}发送的数据.
有人可以给我一个例子如何做到这一点?
你可以使用lambdas和一些像i18next或其他类似的库.
{{#i18n}}greeting{{/i18n}} {{name}}
Run Code Online (Sandbox Code Playgroud)
数据通过:
{
name: 'Mike',
i18n: function() {
return function(text, render) {
return render(i18n.t(text));
};
}
}
Run Code Online (Sandbox Code Playgroud)
这解决了我的问题
这非常简单,也非常直接。
首先,您需要添加代码来确定查询字符串lang。为此,我使用摘自此处答案的片段。
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
Run Code Online (Sandbox Code Playgroud)
然后,我使用 jQuery 来处理ajax和onReady状态处理:
$(document).ready(function(){
var possibleLang = ['en', 'id'];
var currentLang = getParameterByName("lang");
console.log("parameter lang: " + currentLang);
console.log("possible lang: " + (jQuery.inArray(currentLang, possibleLang)));
if(jQuery.inArray(currentLang, possibleLang) > -1){
console.log("fetching AJAX");
var request = jQuery.ajax({
processData: false,
cache: false,
url: "data_" + currentLang + ".json"
});
console.log("done AJAX");
request.done(function(data){
console.log("got data: " + data);
var output = Mustache.render("<h1>{{title}}</h1><div id='content'>{{content}}</div>", data);
console.log("output: " + output);
$("#output").append(output);
});
request.fail(function(xhr, textStatus){
console.log("error: " + textStatus);
});
}
});
Run Code Online (Sandbox Code Playgroud)
对于这个答案,我尝试使用简单的 JSON 数据:
{"title": "this is title", "content": "this is english content"}
Run Code Online (Sandbox Code Playgroud)
获取此 GIST以获得完整的 HTML 答案。
| 归档时间: |
|
| 查看次数: |
6002 次 |
| 最近记录: |