我有一个使用 Jade 模板引擎运行的 node.js express 服务器。
我有一个布局文件,它可以像这样导入单个 View 的主体:
!!!
html
head
title= title || 'Title not set.'
body
#header
h1 Header.
#content!= body //- this renders the body of an individual view
#footer
p Footer.
例如以下索引页面:
p Welcome to the front page.
p This page serves as a now.js test.
这很好用。但是,我现在想包含两个专门用于该索引页面的客户端 javascript 库(因此不是每个页面,这就是为什么我不能将它放在布局的头部)。
这行得通:
//- import jquery
script(type='text/javascript', src='./jquery-1.5.2.min.js');
//- import now.js (hosts itself)
script(type='text/javascript', src='/nowjs/now.js')
//- import the chat client
script(type='text/javascript', src='./indexChatClient.js')
p Welcome to the front page.
p This page serves as a now.js test.
但是,这会将脚本加载到完整页面的正文中,这不是有效的 HTML,对吧?
据我所知,如果我想正确执行,脚本应该加载到头部,但头部部分由布局文件处理。
那么,我该如何正确地包含这些专门针对某个 View /页面的客户端 JavaScript 库?
最佳答案
您可以将它们放在布局上,并指定要在“ Controller ”上加载哪些库。
// layout.jade
!!!
html
head
title= title || 'Title not set.'
-each script in scripts
script(type='text/javascript', src= script)
body
#header
h1 Header.
#content!= body //- this renders the body of an individual view
#footer
p Footer.
还有你的“控制者”:
// app.js
app.get('/', function (req, res) {
res.render({
scripts: ['jquery.min.js', '/nowjs/now.js']
}
}
关于javascript - 带有 Express : Importing client-side javascript using script tags in Jade views? 的 Node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5605392/