Shend
Shend

Reputation: 95

How to include CSS files in Express.js views when not using a template engine?

I'm trying to create an Express application. My limitations are that I cannot use any template engine for rendering HTML. There are (at least) two problems:

  1. One of the problems that I foresee is how will I manage to manipulate the data based on what I need to show to the user. E.g. I have a transactions table in my database and I need to display an HTML table of all those transactions. The traditional way that I'm used is to utilize a template engine, where I can put a for loop that goes through the records.
  2. I'm sending an HTML file when I call a specific route, but it cannot get the CSS files from another folder.

For problem 2. I've tried:

 app.get('/transactions', (req, res) =>
    res.sendFile(path.join(__dirname+'/public/assets/html/transactions.html')))

and then in transactions.html I have

<link rel="stylesheet" href="../stylesheets/shared/constants.css">
and other links to stylesheets.

When the page is displayed, it doesn't apply any of the styles. When I checked the source code in the browser, and I click the link for constants.css it shows the message:

Cannot GET /stylesheets/shared/constants.css

This doesn't seem like the right logic. What things should be changed?

Upvotes: 0

Views: 1717

Answers (2)

Axel Menard
Axel Menard

Reputation: 11

Simple Example worked for me:

app.use(express.static(__dirname + "/publlic"))
app.get('/', (req, res) => {
app.engine('html', cons.swig);
app.set('view engine', 'html');
res.render('index');
})

// In your html
<link rel="stylesheet" href="/static/stylesheets/shared/constants.css">

With this method, I use engine like you.

Upvotes: 1

1565986223
1565986223

Reputation: 6718

Simple example:

Assuming your folder structure:

app.js
|   +-- public
|   |   +-- stylesheets
|   |   |   +-- shared
|   |   |   |   +-- constants.css
...

You could simply server public folder as static like:

app.use(express.static(__dirname + "/public"))

// In your html
<link rel="stylesheet" href="/stylesheets/shared/constants.css">

With express, it's better to use absolute path over relative path.

Or set up virtual path for your static files like:

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

// In your html
<link rel="stylesheet" href="/static/stylesheets/shared/constants.css">

Upvotes: 2

Related Questions