简体   繁体   English

将CSS添加到EJS

[英]Adding CSS to EJS

Have difficulties linking my css files when using EJS. 使用EJS时,在链接我的CSS文件时遇到困难。 Already looked into other answer but can't figure it out This is the code I used reference for my css file. 已经研究了其他答案,但无法弄清楚这是我在CSS文件中使用的代码。

EJS EJS

    <html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="index.css">
    <title></title>
  </head>
  <body>
    <header>
      <% include header %>
    </header>
</body>
</html>

The css file is in the same directory as the ejs files, the views directory. css文件与ejs文件位于views目录相同的目录中。 Can this cause any problems? 这会引起任何问题吗? The header is just another ejs file with some static html. 标头只是另一个带有静态html的ejs文件。

server: 服务器:

const express = require("express");
const path = require('path');
const app = express();

app.set("views", path.resolve(__dirname, "views"));
app.set("view engine", "ejs");


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

app.get('/', (req, res) => {
  res.render("index");
})

app.listen(3000);

I Eventually want to move my css files in another folder but I was really wondering why this doens't work. 我最终想将我的css文件移动到另一个文件夹中,但我真的很奇怪为什么这不起作用。 Since the files are in the same folder I expected the relative path <link rel="stylesheet" href="index.css"> to work. 由于文件位于同一文件夹中,因此我希望相对路径<link rel="stylesheet" href="index.css">可以工作。

You specified that the static files (css, images, etc) are on the folder "public" : 您指定了静态文件(css,图像等)在文件夹“ public”上:

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

Read : http://expressjs.com/en/starter/static-files.html 阅读: http : //expressjs.com/en/starter/static-files.html

Just move your css on this folder ;) 只需将css移到该文件夹​​上即可;)

edit : 编辑:

You can specify multiple static folder : 您可以指定多个静态文件夹:

app.use("/public1", express.static(__dirname + "/public1"));
app.use("/public2", express.static(__dirname + "/public2"));

But you can add folders in your static folder : 但是您可以在静态文件夹中添加文件夹:

  • /public1/css / public1 / css
  • /public1/lib / public1 / lib

and use it like that in your ejs file : 并像这样在ejs文件中使用它:

<link rel="stylesheet" href="/public1/css/index.css">

The reason it doesn't work is simply because the folder containing your .ejs files is not actually being served . 它不起作用的原因仅仅是因为实际上未提供包含.ejs文件的文件夹。 When rendering a view, express will locate your .ejs file locally on the server and read its contents, but it will not make it available over a HTTP connection. 渲染视图时,express将在服务器上本地定位.ejs文件并读取其内容,但不会通过HTTP连接使它可用。

You can verify this by trying to access the .ejs file directly via your browser. 您可以通过尝试直接通过浏览器访问.ejs文件来验证这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM