Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call methods on mustache variable in a template

I have a mustache template and I would like to call some function on the mustache variables ({{name}} in this case). Specifically, I want to call toLowerCase() method on the name variable.

<tbody>
  <script id="mytemplate" type="text/template">
    {{#cat}}
      <tr data-index="{{age}}-{{name}}"></tr>
    {{/cat}}
  </script>
</tbody>

I tried looking in the mustache docs but I couldn't find out how to do this. I tried doing

  1. <tr data-index="{{age}}-{{name.toLowerCase()}}"></tr>
  2. <tr data-index="{{age}}-{{name}}.toLowerCase()"></tr>

But I'm not getting what I expect. I render the template with this code which gets triggered on document ready.

$(function() {
      $.getJSON('/cats.json', function(data){
        var template = $("#mytemplate").html();
        var view     = Mustache.to_html(template, data);
        $("tbody").html(view);
      });
  })
like image 283
gprasant Avatar asked Dec 06 '13 17:12

gprasant


People also ask

What is in Mustache template?

The Mustache templates consist of tag names surrounded by { { } } (which resemble mustaches – hence the name) and are backed by a model object containing the data for the template.

What is Mustache HTML?

A Mustache tag begins with two opening braces ( {{ ) and ends with two closing braces ( }} ). As you might have guessed, the {{ and }} delimiters are where Mustache gets its name from!

How handlebars JS is different from Mustache JS?

Handlebars. js is an extension to the Mustache templating language created by Chris Wanstrath. Handlebars. js and Mustache are both logicless templating languages that keep the view and the code separated like we all know they should be; Mustache: Logic-less templates.


1 Answers

you need to pass the function as part of the data, like so:

$(function() {
      $.getJSON('/cats.json', function(data){
        data.lower = function () {
          return function (text, render) {
             //wrong line return render(text.toLowerCase());
             return render(text).toLowerCase();
          }
        };
        var template = $("#mytemplate").html();
        var view     = Mustache.to_html(template, data);
        $("tbody").html(view);
      });
  })

and the template:

<tr data-index="{{age}}-{{#lower}}{{name}}{{/lower}}"></tr>
like image 147
kalley Avatar answered Oct 06 '22 04:10

kalley