EJS Templating Example
EJS Template
<table class="table table-striped table-bordered table-responsive">
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Full Name</td>
</tr>
</thead>
<% people.forEach(function(p,i1){%>
<tr>
<td><input class="form-control" data-bindto="people[<%=i1%>].firstName" value="<%=people[i1].firstName %>"></td>
<td><input class="form-control" data-bindto="people[<%=i1%>].lastName" value="<%=people[i1].lastName %>"></td>
<td data-watching="people[<%=i1%>].lastName,people[<%=i1%>].firstName" data-parsewith="people[<%=i1%>].fullName"><%=people[i1].fullName.in() %></td>
</tr>
<% }); %>
<tr>
<td colspan="4">
<button id="addRowBtn" class="btn btn-default">Add Row</button>
</td>
</tr>
</table>
JavaScript
var ejs = new EJS({url: './templates/ejstemplate.ejs'});
var Person=function(firstName,lastName){
var Person=this;
Person.firstName=firstName;
Person.lastName=lastName;
Person.fullName={
in: function () {
var lastName = Person.lastName;
if (lastName.length > 0)
lastName = " " + lastName;
else
lastName = "";
return Person.firstName + lastName;
}
}
};
var model=[
new Person("Agatha", "Trunchbull"),
new Person("Jennifer", "Honey"),
new Person("Matilda", "Wormwood")
];
var $htmlDiv=$('#htmlDiv');
GDB({people: model});
$htmlDiv.html(ejs.render({people: model}));
$('body').on('click','#addRowBtn',function(){
model.push(new Person("", ""));
$htmlDiv.html(ejs.render({people: model}));
});