Templating offers a great way to keep your coding concerns separate by allowing you to keep your HTML and JavaScript code separate. There are many templating plugins out there but they all do roughly the same thing so it can be hard to decide on which one to go with.
A great jQuery templating plugin is one by Boris Moore which is quite flexible, full featured and has a simple clean syntax. Below is a simple contacts example.
<h1>Contacts</h1> <!-- Template Container --> <div id="contactContainer"></div> <script id="contactTemplate" type="text/html"> <div> Name: {{= name }} <br /> Phone: {{= phone }} </div> </script>
You can see the {{= name }}
and {{= phone }}
expressions which will be replaced with out data. To use the templating engine first we’ll need to include the jQuery plugin.
<script src="./lib/jquery.tmpl.js" type="text/javascript"> <script type="text/javascript"> var contacts = [ {name: "Rob", phone: "555-555-5555"}, {name: "Bob", phone: "666-666-6666"}, {name: "Job", phone: "777-777-7777"} ]; $('#contactTemplate').render(contacts).appendTo('#contactContainer'); </script>
You can see the rendering actually occurs when we call render()
with our contacts
data. It will then automatically loop through the list for us and spit out the elements for us. In this case we have appended them to our #contactContainer
element.
Doing work without a templating engine is almost unheard of these days so it’s a good idea to get used to using them. Although there are many templating plugins to choose from for jQuery, the jquery.tmpl plugin is a great place to start if you are new to things.