0

// I have below code in a html page. I am trying this to learn Handlebars.compile function.

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js">
</script>
    
<script>
    // compile the template
  let template = Handlebars.compile("Hello {{message}}");
  // execute the compiled template and print the output to the console
  console.log(template({ message: "My friend" }));
</script>

//this outputs in console as - Hello
//But when I test this from console for the same page, like for example

let template2 = Handlebars.compile("Hello {{message}}");
console.log(template2({ message: "My friend" }));
//It outputs - Hello My friend

//I am wondering why same is not working from the page.
Magnetism
  • 13
  • 3
  • The page version works just fine for me. – 76484 Jul 26 '21 at 23:55
  • @76484 I had the above code in a .hbs file. Does this make a difference? – Magnetism Jul 27 '21 at 02:03
  • Yes, it would make a big difference. Are you trying to execute the template client-side or server-side? – 76484 Jul 27 '21 at 02:11
  • @76484 I am rendering from server js first like res.render("file") then inside file.hbs I have all that code from above. So, I think yes I am trying to execute tmplate from server-side. – Magnetism Jul 27 '21 at 02:29
  • If you are rendering server-side then you do not need the script reference to the Handlebars library and you don't need to call `Handlebars.compile` - the view engine will do the compiling for you. The `message: "My friend"` part would be part of the `res.render` call. See https://www.npmjs.com/package/express-handlebars – 76484 Jul 27 '21 at 02:35
  • I get that. My use case is where I have to render each element in the list which was originally rendered from server, when each element is clicked on the page. I know I don't have all those details in the above code. Basically I am trying to re-render stuff based on user interaction. I don't want to call server-side again since I have all info already passed to client side in the initial rendering. – Magnetism Jul 27 '21 at 02:59
  • Maybe this will be of help: https://stackoverflow.com/a/64419864/3397771 – 76484 Jul 27 '21 at 03:33

0 Answers0