Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

jade (for nodejs) substrings in templates

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:
    each article in featuredNews.rows
                    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

Problem courtesy of: Igor R


Here is a little "truncate_words" function:

function truncate( value, arg ) {
    var value_arr = value.split( ' ' );
    if( arg 

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

Solution courtesy of: Florian Margaine


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

jade (for nodejs) substrings in templates


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription