2

I am trying to use handlebars.js to create and then inject html into a webpage. I'm testing it out using json written inside of the script before attempting to integrate the server. I have checked the json in a validator and it is all good, but I still get an error from the handlebars template claiming "not well-formed".

I read a few other people who were having issues with Cross Origin Requests, but I use Firefox which is the solution they suggest (Q: not well-formed Source File in mozilla firefox)

Could it be something with my handlebars file?

Here is my js code:

var html;
    var data= { "array":[
        {"firstname":"Joe","lastname":"Shmoe"},
        {"firstname":"John","lastname":"Connor"}
        ]};
    console.log(data);
    $.get("templates/coach-list-template.hbs",function(data){
        var template= Handlebars.compile(data);
        var handlebarshtml=template(data);
        console.log(handlebarshtml);
        console.log("Data: "+data);
    },"html"); 

And here is the handlebars code:

{{#each array}}
<div class="row">
    <div class="col-100"> {{firstname}} {{lastname}}</div>
</div>
{{/each}}
Community
  • 1
  • 1
Kaennar
  • 29
  • 1

3 Answers3

1

You need to compile the template, not the data. So, if you have this in your HTML:

<script type="text/x-handlebars-template" id="mytemplate">
  {{#each array}}
  <div class="row">
    <div class="col-100"> {{firstname}} {{lastname}}</div>
  </div>
  {{/each}}
</script>

You compile that template with

var template = Handlebars.compile(document.getElementById('mytemplate').innerHTML);

and then apply the data by using that template:

var html = template(data);
Stewart
  • 1,659
  • 4
  • 23
  • 35
jlahd
  • 6,257
  • 1
  • 15
  • 21
0

The data in your $.get context isn't the variable you defined in the outer scope.
The variable passed to the $.get callback is the result of the get request, for example:

$.get( "ajax/test.html", function( data ) {
    $( ".result" ).html( data );
    alert( "Load was performed." );
});

If you want to use both the request result and your data variable, rename one.

Etheryte
  • 24,589
  • 11
  • 71
  • 116
0

see the answer here: "not well-formed" warning when loading client-side JSON in Firefox via jQuery.ajax

specifically, see the "beforeSend" option

beforeSend: function(xhr){
  if( xhr.overrideMimeType ){
    xhr.overrideMimeType("application/json");
  }
}
catomatic
  • 661
  • 8
  • 10