简体   繁体   中英

Add scripts in express-handlebars from view

I am using Express-Handlebars as my templating engine and I use a layout for all my views. However, I want to be able to add scripts via the view for specific pages. Very much like in this example: is there a way to add CSS/JS later using EJS with nodejs/express

I want to add my scripts after the standard scripts that are used for all pages(bootstrap, jquery). These are placed at the bottom of body in my layout, like so:

<html>
<header>
...
</header>
<body>
...
{{{body}}}

<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
</body>
</html>

How would I go about doing this using Handlebars? Or is my best bet to use EJS? Or can I use both?

Any help is much appreciated, Freece

Never mind! I realized that that method would contradict the foundations of Handlebars. Instead I added the following to my controller:

var scripts = [{ script: '/js/myTestScript.js' }];
...
res.render('contact', { title: 'Kontakt', scripts: scripts });

And in my layout it looks like this:

...
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
{{#each scripts}}
  <script src="{{script}}"></script>
{{/each}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM