jade (for nodejs) substrings in templates

Would anyone please advise how in jade for nodejs I can truncate a string to a number of characters/words, ideally conscious about the HTML markup within the string?

This should be similar to Django's truncatechars/truncatewords and truncatechars_html/truncatewords_html filters.

If this doesn't exist in jade, which way is right to go? I'm starting my first nodejs+express+CouchDB app, and could do it within nodejs code but it seems that filters are much more appropriate. I would also consider writing a filter like this (and others) if I knew how :))

Just a quick illustration:

// in nodejs:
// body variable comes from CouchDB
res.render('home.jade', { title : "test", featuredNews : eval(body)});

// in home.jade template:
    ul.thumbnails
    each article in featuredNews.rows
        a(href="#"+article.slug)
            li.span4
                div.value.thumbnail
                    img(align='left',src='http://example.com/image.png')
                    p!= article.value.description:truncatewords_html(30)

So I've made up the truncatewords_html(30) thing to illustrate what I think it should be similar to.

Will appreciate any ideas!

Thanks, Igor

Here is a little "truncate_words" function:

function truncate( value, arg ) {
    var value_arr = value.split( ' ' );
    if( arg < value_arr.length ) {
        value = value_arr.slice( 0, arg ).join( ' ' );
    }
    return value;
}

You can use it before sending the string to the template, or in the template using a helper method.

cheerio is a nice little library that does a subset of jquery and jsdom. Then it's easy:

app.helpers({
    truncateWords_html : function(html, words){
       return cheerio(html).text().split(/\s/).slice(0, words).join(" ")
    }
})

Then, in a jade template use:

#{truncateWords_html(article.value.description, 30)}

This looks like a generic way to add any filters, hurray! :))