Handlebars JS Example 1

by megaadriano

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.1.0/handlebars.min.js"></script>
<script src="https://momentjs.com/downloads/moment-with-locales.js"></script>
<h1>Handlebars JS Example</h1>
<script id="some-template" type="text/x-handlebars-template"> <table>
    <thead> 
        <th>Name</th> 
        <th>Job Title</th> 
        <th>Twitter</th> 
        <th>Job Title</th> 
        <th>Date Birth</th> 
    </thead> 
    <tbody> 
        {{#users}} 
        <tr> 
            <td>{{fullName person}}</td> 
            <td>{{jobTitle}}</td> 
            <td><a href="https://twitter.com/{{twitter}}">@{{twitter}}</a></td> 
            <td>{{jobTitle}}</td> 
            <td>{{formatTime person.dateBirth "DD/MM/YYYY"}}</td> 
        </tr> 
        {{/users}} 
    </tbody> 
</table> 
</script>

CSS

body {
    font:15px arial,sans-serif;
}
h1 {
    margin: 0 0 10px 0;
    padding: 5px;
    font-size: 24px;
    background-color: #999;
    color: #fff;
}
table {
    margin: 10px;
}
th, td {
    padding: 5px;
    border: 1px solid #999;
}
th {
    background: #ccc;
}
tr:nth-child(odd) {
    background: #eee;
}
td a {
    color: #000;
    text-decoration: underline;
}

JavaScript

Handlebars.registerHelper('formatTime', function (date, format) {
    var mmnt = moment(date);
    return mmnt.format(format);
});

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

var data = { 
    users: [ { 
        person: {
            firstName: "Garry", 
            lastName: "Finch",
            dateBirth:new Date(2018,1,20,0,0,0,0)
        },
        jobTitle: "Front End Technical Lead",
        twitter: "gazraa" 
    }, {
        person: {
            firstName: "Garry", 
            lastName: "Finch"
        }, 
        jobTitle: "Photographer",
        twitter: "photobasics"
    }, {
        person: {
            firstName: "Garry", 
            lastName: "Finch",
            dateBirth:new Date(2019,12,30,0,0,0)
        }, 
        jobTitle: "LEGO Geek",
        twitter: "minifigures"
    } ]
}; 

Handlebars.registerHelper('fullName', function(person) {
  return person.firstName + " " + person.lastName;
});

$('body').append(template(data));