简体   繁体   中英

Handlebars Template Not Rendering - Can See HTML In Firefox Inspector

I have a handlebars template in an external file (user-listing-template.html) which I am dynamically loading via a JQuery Ajax call to retrieve the file, compiling via Handlebars.compile and then displaying in a div. See example code below:

Template file:

<script id="user-listing-template" type="text/x-handlebars-template">
  <h2 class="ui header">User Maintenance</h2>
  <hr>
  <h4 class="text-align-left">Total Users: </h4>
  <br><br>
</script>

JS function to load Template:

function userListroute() {
var source;
    var template;

    $.ajax({
        url: "/templates/user-listing-template.html",
        cache: true,
        success: function(data) {
            console.log('Template Data From File: ' + data);
            source = data;
            console.log('Template HTML ' + source);
            template = Handlebars.compile(source);
            console.log('Compiled Template: ' + template);

            $('#app').html(template);

        }               
    });  
}

In index.html, I have a div where I would hope to see the template:

<div id="app"></div>

However, when I run this application the template is not rendered. I can see the template's HTML code in the Inspector in Firefox dev tools:

Firefox Inspector Output

All of the console.log() statements show the valid HTML code is there, however it will not display, I only see the blank page. The console output is shown here:

Firefox Console Output

I am clearly doing something wrong, just not sure what - it all appears to be working except for the rendering bit.

Any assistance greatly appreciated. I'm fairly new to Handlebars, and am just trying a proof-of-concept application.

According to official site http://handlebarsjs.com/ . You just compile your template without generating html.

template = Handlebars.compile(source);
var html = template(yourdata);     // yourdata is the object rendered to your template
$('#app').html(html);   // can not be template variable, variable html is final html content

When you retrieve your template file you are leaving it encapsulated with <script> tags. Handlebars needs the content only. Thus (as you can see in Firefox inspector) the compiled output is not displayable HTML as it is still within the original script tags.

You need to extract the HTML from your data when you assign it to the source variable.

success: function( data ) {
    source = $( data ).html();
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM