如何在Mustache模板中使用jQuery内置函数 [英] How to use jQuery built in functions in Mustache template
本文介绍了如何在Mustache模板中使用jQuery内置函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个mustache.js模板
I have a mustache.js template
<script id="catagorie_list" type="text/template">
{{#rows}}<li><a href="#">{{catagorie_name}}</a></li>{{/rows}}
</script>
其中,我想要为每个 {{catagorie_name}创建第一个字母}
作为大写字母。
示例:
in it, I want to make first letter of each {{catagorie_name}}
as Capital Letter.
Example:
india --> India
australia-->Australia
有可能吗?
推荐答案
假设输入对象是:
var countries = {
"rows": [
{ "catagorie_name": "india" },
{ "catagorie_name": "australia" },
{ "catagorie_name": "spain" }
]
};
我们附加一个函数:
var func_var = {
"capitalize_name": function () {
return firstcap(this.catagorie_name);
}
};
jQuery.extend( countries, func_var ); // https://stackoverflow.com/a/10384883/1287812
function firstcap(str) { // https://stackoverflow.com/a/11370497/1287812
var len = str.length;
var re = /^\s$/;
var special = true; // signalizes whether previous char is special or not
for (var i=0; i<len; i++) {
var code = str.charCodeAt(i);
if (code>=97 && code<=122 && special) {
str = str.substr(0, i) + String.fromCharCode(code-32) + str.substr(i+1);
special = false;
}
else if (re.test(str[i])) {
special = true;
}
}
return str;
}
最后,模板:
<script id="catagorie_list" type="x-tmpl-mustache">
<ul>{{#rows}}<li><a href="#">{{capitalize_name}}</a></li>{{/rows}}</ul>
</script>
这篇关于如何在Mustache模板中使用jQuery内置函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文