Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 679
user1292810 Avatar asked Apr 13 '12 09:04

user1292810


People also ask

How do you concatenate handlebars?

The {{concat}} helper is designed to concatenate and link multiple things together. The {{concat}} helper will take all of the items passed to it, treat them as strings, and concatenate them together without any spaces. There can be an unlimited amount of items passed to the helper.

What is a handlebar expression?

Handlebars expressions are the basic unit of a Handlebars template. You can use them alone in a {{mustache}} , pass them to a Handlebars helper, or use them as values in hash arguments.

How do you escape curly braces with handlebars?

Declare a template in the HTML file. Handlebars expressions are put into double curly braces {{expr}} for HTML-escaped content; otherwise, use triple curly brackets {{{expr}}} to avoid HTML-escaping.


1 Answers

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>
like image 196
Noah Rosenberg Avatar answered Sep 17 '22 01:09

Noah Rosenberg