Work with Handlebar.js

I really tried to find some tutorials on Handlebar.js and I found this http://javascriptplayground.com/blog/2012/05/javascript-templating-handlebars-tutorial

But it does not work as expected.

What I am doing is the index.html file,

<html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.js" type="text/javascript" charset="utf-8"></script> <script src="app.js" type="text/javascript" charset="utf-8"></script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Messing with Handlebars</title> </head> <body> <script id="ajax-comment" type="text/x-handlebars-template"> <li> <span class="meta">{{name}} on {{date}}</span> <p>{{comment}}</p> </li> </script> </body> </html> 

and app.js , which contains the code.

 var source = $("#ajax-comment").html(); var template = Handlebars.compile(source); var data = { name : "Jack", date : "12/04/12", comment : "This is a really awesome tutorial. Thanks." }; $("ul").append(template(data)); 

But all I get is a blank page. Any mistake I am making here? Detailed explanations will be helpful.

+6
source share
3 answers

"ul" element does not exist, you must add it to what actually exists.

just add <ul></ul> somewhere in the body.

the violin is here

+3
source

You might want to check the answer to this question. It looks like the jquery function did not have access to the element, since the DOM was not loaded before the call was made. I tried several combinations after the initial changes to calling the app.js code (without wrapping it inside the function) only after loading the DOM, which worked. For example, I moved the script call just before </body> , which also worked.

... <script src="app.js" type="text/javascript" charset="utf-8"></script> </body>

It also helped me find out if we use HTML or XHTML as our type of document to better understand this problem.

0
source

try putting ref on your external JS below, just above the closing body tag

eg,

 <body> <ul></ul> <!-- last thing on the page--> <script src="app.js" type="text/javascript"></script> </body> 

it seemed to solve it for me

0
source

Source: https://habr.com/ru/post/924566/


All Articles