An Easy Way to Get a List of Your Tweets with Handlebars!

Programming

In my JavaScript template engines.

There are various template engines, as an example we will take Handlebars.

The template is made as follows:

<script id="entry-template" type="text/x-handlebars-template">
         Template content
</script>

Scripts with unknown type (as in the example above) are simply ignored by the browser and search systems. It’s a good way to obscurely insert templates into the website. 

Handlebars template

The template for tweets output from previous post will be as follows:

<script id="tweets-template" type="text/ x-handlebars-template">     {{#each tweets}}     <div class="tweet">        <div class="avatar">            <a href="http://twitter.com/{{user.screen_name}}" target="_blank">              <img src="{{user.profile_image_url}}"/>            </a>        </div>               <div class="user">            <a href="http://twitter.com/{{user.screen_name}}" target="_blank"> {{user.name}}            </a>        </div>                     <div class="time">{{formatDate created_at}}</div>        <div class="txt">     <a target="_blank" href="https://twitter.com/{{user.screen_name}}/status/ {{id_str}}">{{text}}</a>        </div>     </div>     {{/each}} </script>

Variables that should be inserted into definite places are marked by {{ }}.  We have the list of tweets for an output, so in this peculiar case we sort out all the tweets with the help of {{#each tweets}} … {{/each}} construction.

Now we have to estimate the template we want to use and redirect it to Handlebars for compilation:

    var source   = $("#tweets-template").html();
var template = Handlebars.compile(source); 

The next step is to set our previously formed tweets list into the template:

var content = {
tweets : [
{obj1},
{obj2},
{…}
]
}
var html = template(content);
$('.tweets').html(html);

Little styling and we receive such list:

Tweets list with Handlebars

Handlebars allows using helpers, which can be further used in templates. We use one helper as an example:

Handlebars.registerHelper('formatDate', function(date) {
return date.substr(0, 19);
});

In order to use this helper to set the date, we add «formatDate created_at».

That is how we can make use of this template engine. Surely its functionality is not restricted to the case described above, it has a lot more functions and possibilities to be used. Any further information can be found at www.handlebarsjs.com

See also: Retina Display and 5 Ways to Optimize It

Comments