有没有办法稍后使用带有nodejs / express的EJS添加CSS / JS
我正在使用带有nodejs / express的EJS模板引擎,我想知道是否可以在index.ejs(而不是layout.ejs)中添加另一个css或js文件
layout.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<link rel='stylesheet' href='/stylesheets/smoothness/jquery-ui-1.8.14.custom.css' />
</head>
<body>
<%- body %>
</body>
</html>
index.ejs
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
我不想在每个模板中添加第二个css文件,只有index.ejs - 有什么方法可以做到吗?
回答如下:在这里找到了一个解决方案:Node.js with Express: Importing client-side javascript using script tags in Jade views?
它使用的是玉而不是EJS,但工作方式完全相同。这里有一些快递2.4.0的代码片段。
你必须在你的app.js中添加以下“帮助者”
app.helpers({
renderScriptsTags: function (all) {
if (all != undefined) {
return all.map(function(script) {
return '<script src="/javascripts/' + script + '"></script>';
}).join('\n ');
}
else {
return '';
}
}
});
app.dynamicHelpers({
scripts: function(req, res) {
return ['jquery-1.5.1.min.js'];
}
});
layout.ejs看起来像这样:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<%- renderScriptsTags(scripts) %>
</head>
<body>
<%- body %>
</body>
</html>
如果你没有向scripts-array添加任何脚本,只会包含'jquery-1.5.1.min.js' - 如果你想将文件添加到子页面,你可以这样做:
test.ejs
<% scripts.push('jquery-ui-1.8.14.custom.min.js', 'jquery.validate.min.js') %>
<h1><%= title %></h1>
<p>I'm a template with 3 js files in the header</p>
而已。