简体   繁体   中英

How to link css to ejs templates in node

I am working on a beginner node js server. I am able to render dynamic html using ejs templates but i cannot link css styling to them

I have set up a public directory to store the assets like images and external css files. i have linked to the static contents to express using

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

my public folder has images(.jpg) which are rendered but the css in the public folder cannot be rendered.

file structure : 
node_modules
models
views
public > app.css, hero.jpg
server.js
package.json

the express app is as below : server.js

const express = require('express');
const app = express();
const ejs = require('ejs');
app.use('/public', express.static(__dirname + '/public');
app.set("view engine", "ejs");
app.set('views',__dirname+'/views');
app.get('/', (req,res) =>{
   res.render('home',{
        title: "HomePage",
        date : new Date().getFullTYear()
        }
app.listen(3000);

the home.ejs file has a head section as :

<head>
<meta charset = "utf-8">
<title> My Website <%= title %> </title>
<link rel="stylesheet" href="/app.css" type="text/stylesheet">
</head>

I expected the app.css to load like the in the home.ejs file. But its not working

Looking at your code, I could guess you are setting the static file folder to be /public.

Try modifing you css link to <link rel="stylesheet" href="/public/app.css" type="text/stylesheet">

or try setting the static file config like this:

app.use('/static', express.static(path.join(__dirname, 'public')))

and then <link rel="stylesheet" href="/static/app.css" type="text/stylesheet">

You should declare your public folder this way

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

That means you can serve these files as if these were in the root folder. So you can link your css and images this way

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


// in case of image
<img src="/hero.jpg">


When you declare public folder like this

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

you set a virtual path prefix for your files and in that case you have to add public in the url path of each file, like this <link rel="stylesheet" href="/public/app.css" type="text/stylesheet">

To use the absolute path of the directory that you want to serve as a part of public folder:

app.use(express.static(path.join(__dirname, 'public')));

Create public folder under the root folder. Under that folder create css folder if you want. So, structure will be link public/css/style.css

You can access style.css like:

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

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