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.
Create a helper for adding css/js files.
Create a file. Call it
helpers.js
with the following content.While creating the handlebar instance, attach the above helper.
exphbs.create({ extname :'hbs', defaultLayout: 'layout', helpers : require('PATH-TO/helpers'), });
In
layout.hbs
, render the tags by adding{{{renderJS js}}}
before</body>
Attach route based js files to view data.
res.render('/foo', { 'js': ['/path/to/1st-custom-js.js', 'path/to/2nd-custom-js.js'] });