将.css文件添加到ejs

即时通讯工作与ejs node.js(expression),即时通讯不能够包括一个.css文件it.i尝试单独作为一个html-css二重奏相同的事情,它工作正常…我怎么能包括在我的.ejs文件。 我的app.js如此:

var express = require('express'); var app = express(); app.set('views', __dirname + '/views'); app.get('/', function(req, res){ res.render('index.ejs', { title: 'My Site', nav: ['Home','About','Contact'] }); }); app.get('/home', function(req, res){ res.render('index.ejs', { title: 'My Site', nav: ['Home','About','Contact'] }); }); app.get('/about', function(req, res){ res.render('about.ejs', { title: 'About', nav: ['Home','About','Contact'] }); }); app.get('/contact', function(req, res){ res.render('contact.ejs', { title: 'Contact', nav: ['Home','About','Contact'] }); }); app.listen(3000); 

和index.ejs文件:

 <html> <head> <link href="style.css" rel="stylesheet" type="text/css"> </head> <body> <div> <h1> <%= title %> </h1> <ul> <% for (var i=0; i<nav.length;i++) {%> <li><a href="/<%=nav[i]%>"> <%=nav[i]%> </a></li> &nbsp; <% } %> </ul> </div> <br> <h3>Node.js</h3> <p class='just'>Express is agnostic as to which templating language you use. Templating languages can be a hot topic of debate.Here Iam going to use Jade.</p> <p class ='just'>Again Express is agnostic to what you use to generate your CSS-you can use vanilla CSS but for this example I'm using Stylus. </p> <footer> Running on node with express and ejs </footer> </home> </html> 

style.css文件:

 <style type="text/css"> body { background-color: #D8D8D8;color: #444;} h1 {font-weight: bold;text-align: center;} header { padding: 50px 10px; color: #fff; font-size :15px; text-align:right;} p { margin-bottom :20px; margin-left: 20px;} footer {text-decoration: overline; margin-top: 300px} div { width:100%; background:#99CC00;position:static; top:0;left:0;} .just { text-align: center; } a:link {color:#FF0000;} /* unvisited link */ a:visited {color:#0B614B;} /* visited link */ a:hover {color:#B4045F;} /* mouse over link */ a:active {color:#0000FF;} ul { list-style-type:none; margin:0; padding:0;text-align: right; } li { display:inline; } </style> 

你的问题实际上并不是特定于ejs的。

这里需要注意两点

  1. style.css是一个外部的css文件。 所以你不需要那个文件里面的样式标签。 它应该只包含CSS。

  2. 在您的快速应用程序中,您必须提及您从中为静态文件提供服务的公共目录。 像css / js / image一样

它可以通过

 app.use(express.static(__dirname + '/public')); 

假设你把css文件放在你的应用程序根目录下的公用文件夹中。 现在你必须引用你的模板文件中的css文件,比如

 <link href="/css/style.css" rel="stylesheet" type="text/css"> 

在这里,我假设你已经将css文件放在公用文件夹内的css文件夹中。

所以文件夹结构将是

 . ./app.js ./public /css /style.css 

你可以使用这个

  var fs = require('fs'); var myCss = { style : fs.readFileSync('./style.css','utf8'); }; app.get('/', function(req, res){ res.render('index.ejs', { title: 'My Site', myCss: myCss }); }); 

把这个模板

  <%- myCss.style %> 

只是build立style.css

  <style> body { background-color: #D8D8D8; color: #444; } </style> 

我尝试了一些自定义的CSS。 这个对我有用

 app.use(express.static(__dirname + '/public'));<link href="/css/style.css" rel="stylesheet" type="text/css"> 

所以文件夹结构应该是:

 . ./app.js ./public /css /style.css