Question

Is there any way in Mustache of limiting the number of characters a Mustache tag generates?

eg

template = "<li>{{my_tag}}</li>"

data = {
    "my_tag" : "A very long string that needs to be abbreviated to fit into the available space."
}

Now when I render my tag I want to abbreviate the long string by showing only the first 10 chars follwed by an ellipsis. I looked into using a lambda function (as described in the Mustache docs) like so...

template = "<li>{{#limitLength}}{{my_tag}}{{/limitLength}}</li>"

data = {
    "limitLength" : function() {
        return function(text) {
          return text.substr(0,10) + '...';
        }
      },
    "my_tag" : "A very long string that needs to be abbreviated to fit into the available space."
}

but unfortunately the {{my_tag}} tag doesn't get expanded. The Mustache manual states:

The text passed is the literal block, unrendered. {{tags}} will not have been expanded - the lambda should do that on its own.

.. but I can't imagine how to do this without using the Mustache.to_html() function and when I try to use it like so...

eg

data = {
    "limitLength" : function() {
        return function(text) {
          return Mustache.to_html(text,data).substr(0,10) + '...';
        }
      },
     "my_tag" : "A very long string that needs to be abbreviated to fit into the available space."
}

... it fails silently (the recursive use of the data object is possibly to blame here)

Does anyone know of any other way of achieving this without resorting to a javascript/jQuery function, I'd like to implement it just using Mustache if possible.

Was it helpful?

Solution

Your function actually gets called with two arguments: the unrendered text and a render function which can be used to render your text, keeping the current context.

data = {
    "limitLength" : function() {
        return function(text, render) {
          return render(text).substr(0,10) + '...';
        }
      },
     "my_tag" : "A very long string that needs to be abbreviated to fit into the available space."
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top