有没有办法使用EJB与nodejs / express稍后添加CSS / JS [英] is there a way to add CSS/JS later using EJS with nodejs/express
问题描述
我正在使用具有nodejs / express的EJS模板引擎,我想知道是否可以添加另一个css或js文件,例如index.ejs(而不是layout.ejs)
i'm using the EJS template engine with nodejs/express and i'm wondering if it's possible to add another css or js file in e.g the index.ejs (not the layout.ejs)
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 - 有没有办法我可以这样做?
i don't want to add the second css file in every template but only the index.ejs - is there any way i can do that?
推荐答案
在这里找到一个解决方案: Node.js with Express:使用Jade视图中的脚本标签导入客户端javascript ?
found a solution here: Node.js with Express: Importing client-side javascript using script tags in Jade views?
它使用的是玉而不是EJS,但工作原理一样。
这里是一些代码片段,用于表达2.4.0。
it's using jade instead of EJS but works all the same. here are some code-snippets for express 2.4.0.
您必须在您的app.js中添加以下helpers$ / b
$ b
you have to add the following "helpers" to your 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>
如果不向脚本数组添加任何脚本,只能使用'jquery-1.5.1将包括.min.js' - 如果要将文件添加到子页面,可以这样做:
if you don't add any scripts to the scripts-array, only 'jquery-1.5.1.min.js' will be included - if you want to add files to a subpage you can do this like so:
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>
就是这样。
这篇关于有没有办法使用EJB与nodejs / express稍后添加CSS / JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!