Back to Top

HTML templating using JQuery

Updated 16 July 2021

JQuery is a preeminent library of Javascript that provides you robust methods to manipulate DOM. The main aim of this article to let you know the technique of manipulating DOM and provide a wonderful user interface experience.

JQuery templating let you render JSON to HTML elements. Suppose you have a video records having a title and image in your database and you want to show a video listing in your portal just like other video channels does. Here in this blog, I will show you how to make a template and render it using JSON without using any external library like handle.js

Below is the JSON response to my API http://ashok.webkul.com/vikash/video-list.php for video listings

[
   {
      "title":"vidya vox jukebox 2017",
      "img":"https:\/\/i.ytimg.com\/vi\/QfpgUe7jsr0\/hqdefault.jpg?sqp=-oaymwEWCMQBEG5IWvKriqkDCQgBFQAAiEIYAQ==&rs=AOn4CLC69mA9WAL1i8K63zwiZSKOH1SKBg"
   },
   {
      "title":"The Best Songs Of Spotify",
      "img":"https:\/\/i.ytimg.com\/vi\/hRgLyEPBxEc\/hqdefault.jpg?sqp=-oaymwEWCMQBEG5IWvKriqkDCQgBFQAAiEIYAQ==&rs=AOn4CLCHauwQWwhKmH_JOAIajWYHNmx4Tg"
   },
   {
      "title":"10 PLANTS THAT EAT ANIMALS",
      "img":"https:\/\/i.ytimg.com\/vi\/oASwAfCsQEE\/hqdefault.jpg?sqp=-oaymwEWCMQBEG5IWvKriqkDCQgBFQAAiEIYAQ==&rs=AOn4CLCJbGlEDzRNebP7LjchnX_31ukBhw"
   }
]

Here are two way to make an interactive template

1. Using script tag

<html>
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
         //using bootrap just for design purpose 
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    </head>
    <body>
        <div class="container">
            <script id="blog" type="template">
                <div class="col-md-3">
                    <div class="thumbnail">
                        <img src="{{image}}" class="img-rounded img-responsive" width="100%"></img>
                        <div class="caption">
                            <p>{{title}}</p>
                        </div>
                    </div>
                </div>
            </script> 
        </div>   
        <script>
         $(function() {
            $.ajax({
                url: 'http://ashok.webkul.com/vikash/video-list.php',
                success: function(content) {
                    var temp = $.trim($('#blog').html());
                    $.each(JSON.parse(content), function(index, obj) {
                        var x = temp.replace(/{{title}}/ig, obj.title).replace(/{{image}}/ig, obj.img);
                        $('.container').append(x);
                    });
                }
            })
         });
        </script>
    </body>
</html>

I have written a thumbnail inside #blog script tag that will work as a template form me. I am using {{  }} for wild card varianbles, You may put your own wildcard like what ever you want.

Consider code in line 9-18 inside ajax success function I am calling my template using #id

Start your headless eCommerce
now.
Find out More
var temp = $.trim($('#blog').html());

replace all the wild card variables with its corresponding values from the javascript object

var x = temp.replace(/{{title}}/ig, obj.title).replace(/{{image}}/ig, obj.img);

2. Using placeholder

<html>
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    </head>
    <body>
        <div class="container"></div>

        <script>
         $(function() {
            $.ajax({
                url: 'http://ashok.webkul.com/vikash/video-list.php',
                success: function(content) {
                    $.each(JSON.parse(content), function(index, obj) {
                        $('.container').append(
                            `<div class="col-md-3">
                                <div class="thumbnail">
                                    <img src="${obj.img}" class="img-rounded img-responsive" width="100%"></img>
                                    <div class="caption">
                                        <p>${obj.title}</p>
                                    </div>
                                </div>
                            </div>`
                        );
                    });
                }
            })
         });
        </script>
    </body>
</html>

Thanks to javascript’s template literal back-tick (` `)  and placeholder ${ } that makes our task easier with respect to method 1. Here we just put our template thumbnail inside ajax success function and populate our placeholders with its corresponding values.

. . .

Leave a Comment

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


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home