Search code examples
jquerytruncatedust.js

Truncating returned data in Dust.js template


We are outputting into a Dust.js template, like so:

{#Data}
<li class="link-block clearfix">
    <img class="profile-image" src="{ImagePath}"/>
    <div class="left">
        <a href="{UrlPath}">
            <span class="left">
                <span class="details">{ByLineStart}{ByLineAction}{ByLineEnd}</span>
                <p>{Detail}</p>
            </span>
            <span class="left info">
                <span class="last-reply">{Last}</span>
                <span class="count-small">{ChildCount}</span>
            </span>
        </a>
    </div>
</li>
{/Data}

We want to make the "Detail" output truncated in this case at XXX number of characters. Like an RSS feed, the whole block is a clickable area that takes a user into another part of the application. Does anybody have any knowledge of existing Dust Logic that will truncate the value in-line?


Solution

  • None that I know of. But you can try the following

    Creating custom helper

    var dust = require("dustjs-linkedin");
    require("dustjs-helpers");
    dust.helpers.Truncate = function(chunk, context, bodies, params) {
        var data   = dust.helpers.tap(params.data, chunk, context),
            length = dust.helpers.tap(params.length, chunk, context);
        return chunk.write(data.substr(0, length));
    }
    

    Template

    {@Truncate data="{Detail}" length="15"/}
    

    If the value XXX you specified in the question is a constant value, then you can create a custom filter like this. In this example XXX is taken as 5.

    var dust = require("dustjs-linkedin");
    dust.filters.t = function(value){
        return value.substr(0, 5);
    };
    

    Template

    {Detail|t}