Reputation: 29
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}}
Upvotes: 2
Views: 472
Reputation: 881
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");
}
}
Upvotes: 0
Reputation: 6293
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);
Upvotes: 1
Reputation: 25310
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.
Upvotes: 0