Search code examples
javascripttemplateshandlebars.js

Handlebars - substring


I am new to Handlebars templating system and this is my first project I am working on with Handlebars. I have created simple template:

<script id="article_list_template" type="text/x-handlebars-template">
    {{#each this}}
    <div class='article'>
    <a href='article.php?id={{id_news}}' data-article_id='{{id_news}}'>
        <h1>{{title}}</h1>
    </a>
        <p> {{{content}}} </p>
    <div style='clear: both;'> </div>
    </div>
    {{/each}}
</script>

Returned content is very long. I want it to be shorter, e.g. 150 chars. I was trying to use JavaScript substring() method as follows:

<p> {{{content.substring(0,150)}}} </p>

But it obviously did not work. Could you give me some tips how to deal with that problem. Thanks

Edit: Okay, problem solved: I have done it in PHP, so that returned content has now proper length:

foreach ($articles as $a) {
    $a->content = cut_text( $a->content, 30);
}

Solution

  • You're going to want to create a Handlebars helper in javascript to execute the substring code:

    Handlebars.registerHelper('trimString', function(passedString) {
        var theString = passedString.substring(0,150);
        return new Handlebars.SafeString(theString)
    });
    

    Then, in your template, you'd call it like this:

    <p> {{{trimString content}}} </p>