How to use jQuery built in functions in Mustache template

时光毁灭记忆、已成空白 提交于 2019-12-11 13:18:48

问题


I have a mustache.js template

<script id="catagorie_list" type="text/template">
    {{#rows}}<li><a href="#">{{catagorie_name}}</a></li>{{/rows}}    
</script>

in it, I want to make first letter of each {{catagorie_name}} as Capital Letter. Example:

india --> India

australia-->Australia

Is it possible?


回答1:


Supposing the input object is:

var countries = {
  "rows": [
    { "catagorie_name": "india" },
    { "catagorie_name": "australia" },
    { "catagorie_name": "spain" }
  ]
};

We append a function to it:

var func_var = {
    "capitalize_name": function () {
        return firstcap(this.catagorie_name);
      }
};
jQuery.extend( countries, func_var ); // https://stackoverflow.com/a/10384883/1287812

The capitalization function:

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;
}

And finally, the template:

<script id="catagorie_list" type="x-tmpl-mustache">
    <ul>{{#rows}}<li><a href="#">{{capitalize_name}}</a></li>{{/rows}}</ul>
</script>



回答2:


Use CSS, you might want to set a class like this on your a tag

.capitalize {text-transform:capitalize;}

And then your original code would look like

<script id="catagorie_list" type="text/template">
    {{#rows}}<li><a class="capitalize" href="#">{{catagorie_name}}</a></li>{{/rows}}    
</script>


来源:https://stackoverflow.com/questions/24202159/how-to-use-jquery-built-in-functions-in-mustache-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!