HTML Template with JQuery

Yes, you heard right, there are tons of new JS frameworks which are more powerful with this stuff like react native, angular, backbone, knockout, ember and the list goes on.

But our old favorite JQuery and it’s tons of plugins still has almost like 80% of the Internet market share.

Often you need to perform ajax calls and load dynamic data into your html from Ajax calls. If you are like the most people, you’ve probably done with declaring html markup in javascript variables and then append it. like

    <ul id="result">
var li = '<li>'this is my data'+data.value</li>';

Yes its very easy and manageable if you just have to print these li but what if you need to display address, names, telephone numbers of users in a bootstrap cards layout. You will write the whole card layout in your JS, e.g.

var htmlTemplate = '
'<div class="card">'+
  '<div class="card-header">'+
  '<div class="card-body">'+
   ' <div class="telephone">'+
    '<div class="address">'+

This code is beginning to smell now. And soon as the requirements raises, code will become unmanageable, unreadable, and prone to errors and bugs. What if I tell you there is a cleaner and more manageable way to do that.

So here are the steps to do that:

  • Create the html template at bottom of your page like this:
<div class="card">
  <div class="card-header">
  <div class="card-body">
    <div class="telephone">
    <div class="address">

Now set this template block’s visiblity to none.

  • Now add this html based template visibility to none
  • Get that whole template element with jquery
  • Clone the element with jquery’s clone()
  • replace the variables in {} with your data
  • append the final element to the content area of your html.

Leave a Reply

Your email address will not be published. Required fields are marked *