Inserting template code below code in Handlebars layout.hbs

1.4k views Asked by At

I am working with an Express Handlebars project and have a template foo.hbs and it has some javascript I want to insert below the script tags in layout.hbs:

<!DOCTYPE html>
<html>
  <head>
    <title>{{title}}</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    {{{body}}}
  <script type="text/javascript" src="../bower_components/jquery/dist/jquery.js"></script>
  <script type="text/javascript" src="../bower_components/bootstrap/dist/js/bootstrap.js"></script>
  <!-- INSERT custom code here -->
  </body>
</html>

So if foo.hbs was this:

<p>Hello World</p>
<!-- Want to insert this below script tags in layout.hbs -->
<script>
    // Some script that requires jQuery
</script>

Any ideas?

Cheers.

1

There are 1 answers

0
Swaraj Giri On BEST ANSWER

Create a helper for adding css/js files.

  1. Create a file. Call it helpers.js with the following content.

  2. While creating the handlebar instance, attach the above helper.

    exphbs.create({ extname :'hbs', defaultLayout: 'layout', helpers : require('PATH-TO/helpers'), });

  3. In layout.hbs, render the tags by adding {{{renderJS js}}} before </body>

  4. Attach route based js files to view data.

    res.render('/foo', { 'js': ['/path/to/1st-custom-js.js', 'path/to/2nd-custom-js.js'] });