Search code examples
javascriptjqueryhtmlhandlebars.jstemplating-engine

jQuery.handlebars template not rendering on dynamic DOM appending


I have been using dynamic DOM appending for initializing my app, using jQuery.handlebars as the templating library. But the problem with the jQuery.handlebars is that it does not render template to a dynamically invoked DOM. Example

   $(document).ready(function(){
         $('body').append('<div id="content"></div>');
         $('#content').render('default', {

         });
   )};

default is the template file default.hbs with all templates path properly initialized.

but it works in the case where

index.html

    <div id="#content"></div>

the jQuery file

    $('#content').render('default', {

    });

Another problem with jQuery.handlebars is that it does not append any element in the template using jQuery. Example

default.hbs

    <div id="#append-content"></div>

the jQuery code

     $('#append-content").html('Hi');

but content "Hi" does not appear.

It is kinda confusing, please enlighten if its wrong or if any disapproval regard usage of jQuery.handlebars, please suggest a new templating library to go with.


Solution

  • jquery.handlebars render method is asynchronous. You are trying to append to the container before the rendering is complete. The render method triggers a 'render.handlebars' event when its done rendering. Do your DOM manipulation in a callback.

    $('#content').render('template', {
    
    }).on('render.handlebars', function() {
      $('#append-content').html("hello");
    });