Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Content truncation which ends with "..." #111

wants to merge 2 commits into


None yet
5 participants

akoenig commented Aug 7, 2011

In my current project it was necessary for me to truncate the strings within a template to a specific length and add the omnipresent "...".

I thought it would be cool if there is a notation for mustache tags to handle this problem. So I've implemented a small modification of the "render_tags" method. With this it is possible to shorten the string by defining the length within the tag:

{{thetag:20}} -> Shorten the "thetag" content to 20 chars and end up with " ...".

So maybe this is useful for somebody.



janl commented Aug 7, 2011

I'd rather see helpers implemented rather than adding syntax for all these things. See http://writing.jan.io/mustache-2.0.html


akoenig commented on 8db22d3 Aug 11, 2011

Well :)


janl commented Feb 23, 2012

Could be an extra too :) Either way, this would have to be rebased against master/0.5.0-dev

It's a lot easier to do it with handlebars.js and a custom helper function:

<script id="entry-template" type="text/x-handlebars-template">
    <div class="entry">
        <div class="body">
            {{truncate body max=10}}

<script type="text/javascript">
    Handlebars.registerHelper('truncate', function(val, options){ 
        var max = options.hash.max;

        return val.length > max ? val.substring(0,max) : val;

    var source   = $("#entry-template").html();
    var template = Handlebars.compile(source);
    var context = {title: "My New Post", body: "Thisismynewpost"}
    var html    = template(context);

@FiveCornerSquare Yes, but then your template is no longer logic-less :)


nikolas commented Aug 6, 2015

I'm also trying to make a truncation filter using Mustache.js 2.1.3.

How do I pass in a length argument to the filter in the Mustache template? Here's
what I have so far:

    'ellipses': function() {
        return function(text, render, args) {
            console.log(args);  // undefined :P
            var length = 3;
            var str = render(text);
            if (str.length > length) {
                str = str.substring(0, length) + '&hellip;';
            return str;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment