Add scripts in express-handlebars from view

≡放荡痞女 提交于 2019-12-11 05:13:50

问题


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


回答1:


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}}


来源:https://stackoverflow.com/questions/40386257/add-scripts-in-express-handlebars-from-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!