简体   繁体   中英

How to use jQuery built in functions in Mustache template

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?

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM