编辑:我修改了我的 app.js 部分,这样我就可以传入文件并像我对标题所做的那样做一些事情,但由于某种原因它不起作用。
我目前有我的 header.ejs 页面在每个页面上加载索引样式表。
<head>
<title><%= title %></title>
<link rel='stylesheet' href='public/css/style.css'>
<link rel='stylesheet' href='public/bower_components/bootstrap/dist/css/bootstrap.min.css'>
<link rel='stylesheet' href='public/css/index.css'>
</head>
我希望做的是为我所有的样式表设置一个条件加载系统。使用我在该页面上调用 res.render()
时传递的参数。可以设置像我在下面尝试过的东西吗?
<link rel="stylesheet" href="<%= cssFile1 %>">
app.js
app.get('/', function(req, res, index-styles, index-script) {
var pageTitle = getPageTitle('Home');
res.render('index', {
title: pageTitle,
cssFile1: index-styles,
script1: index-script
});
});
/routes/index.js
exports.index = function(req, res, index-styles, index-script) {
res.render('index', {
title: 'Home',
cssFile1: index-styles,
scriptFile1: index-script
});
};
我设法用页面标题设置它,但我是 Express 的新手,我不完全确定当我执行 `<%= cssFile1 %> 时出了什么问题。任何帮助将不胜感激!
最佳答案
如果不同页面有单独的 CSS 文件,我会使用一种设置,其中每个页面特定的 CSS 文件将存储在页面特定的文件(或目录)中:
public/css/index.css // the 'default' file
public/css/home.css // for the 'home' page
public/css/login.css // for the 'login' page
...
然后,在 render
调用中,我将传递应加载的 CSS 文件的名称:
res.render('index', { cssFile : 'login' });
并且在您的 EJS 模板中,如果 cssFile
属性未被传递,则使用它或默认值:
<% var cssFile = cssFile || 'index'; %>
<link rel="stylesheet" href="public/css/<%= cssFile %>.css">
特定于每个页面的任何其他 CSS 文件都可以从特定于页面的 CSS 文件中@import
。
关于javascript - Express 根据当前加载的页面设置样式表的条件加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20438840/