0

I am trying to create reusable components for the different webpages of my website. I started using handlebars.js and I have the code below right now, I am able to pass simple HTML code with it and display it on the webpage. But I would like to have a whole navbar component rendered instead, and preferably linked to from another html or handlebar file somehow. any ideas?

<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.6/handlebars.js"></script>
</head>
<body>
    <script id="template" type="template/handlebars">
        <h1> my website </h1>
        {{>navigationBar}}
    </script>
    <script>
         var partialSrc = "some link to navbar";
         Handlebars.registerPartial("navigationBar",partialSrc);
     var templateSrc = document.getElementById("template").innerHTML;
     var template = Handlebars.compile(templateSrc);
     document.body.innerHTML += template();
    </script>
</body>
mpx
  • 3,081
  • 2
  • 26
  • 56
sunil
  • 41
  • 4

1 Answers1

-1

What do you think about writing the template as string in a variable in an external JS-file and load it separate?

template.js

var templateSrc = '<h1> my website </h1>\
    {{>navigationBar}}';

index.html

<body>
<script src="template.js"></script>
<script type="text/javascript">
  var partialSrc = "some link to navbar";
  Handlebars.registerPartial("navigationBar",partialSrc);
  let template = Handlebars.compile(templateSrc);
  document.body.innerHTML += template();
</script>
</body>

This is a simplified presentation. Ofcourse you have to make sure, that template.js is loaded before compiling with handlebars.

How do I include a JavaScript file in another JavaScript file?

jgrp
  • 32
  • 4