简体   繁体   中英

How to link css file with ejs?

In my directory I have created a public folder in which I have put another folder named css in which is located styles.css. In another folder in my directory named views I have put my ejs file, with which I want to link styles.css like this: <link rel="stylesheet" type="css/text" href="css/styles.css"> However this does not work. I dont even get an error in my browsers console.

If you are using npm and Express, we need to set up a public folder for the static content (like your css file):

1) In your root folder, create a folder called 'public', then another one inside called 'css' and place your styles.ccs file in there.

2) In your JS application file (eg app.js), we need to have something like this:

 //jshint esversion:6 const express = require('express'); const ejs = require("ejs"); const app = express(); app.set('view engine', 'ejs'); app.use(express.static("public")); app.get('/', (req, res) => { res.render('index', { foo: 'FOO' }); });

3) In your root folder, create a folder called 'views' and inside place the EJS file you want to render (eg index.ejs), stablishing the link like this: <link rel="stylesheet" href="/css/styles.css"> :

 <.DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/css/styles.css"> <title>Document</title> </head> <body> <h1>Hello World!</h1> </body> </html>

In this case, you should be able to see the css code applied in the home route "/", rendering the index.ejs file. I hope it help you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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