Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get stylesheet to work with ejs for node.js

I'm trying to make a simple server with node, express and ejs for the template. I've gotten the server to point to the page, load it, and am even able to generate other bits of code with the include statement. However for some reason the style sheet will not load.

app.js

var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
fs = require('fs');

var PORT = 8080; 

app.set('view engine', 'ejs');

app.get('/', function(req, res){
res.render('board.ejs', {
    title: "anything I want",
    taco: "hello world",
    something: "foo bar",
    layout: false
  });
});


app.listen(PORT);
console.log("Server working");

The ejs file is in a directory views/board.ejs

<html>
 <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='../styles/style.css' />
 </head>
 <body >
    <h1> <%= taco %> </h1>
    <p> <%=  something %> </p>
 </body>
</html>

and style.css is in a styles/style.css directory relative to app.js

p {
  color:red;
}

I've tried every path that I can conceive of for the href of the link including relative to where my localhost points relative to app.js relative to board.ejs and even just style.css but none seem to work. Any suggestions are greatly appreciated.

like image 670
Loourr Avatar asked Nov 21 '12 05:11

Loourr


People also ask

How do I use stylesheet in node JS?

create a public folder in main project folder and store a main. css file under css folder in it. Browse: localhost:3000/test/add-username and we will updated css for input field from css file.

Can I use EJS instead of HTML?

As mentioned earlier, EJS is one of the most popular template engines for JavaScript. One of the reasons to choose it is that EJS code looks like pure HTML. It retains the syntax of HTML while allowing data interpolation, unlike Pug (another template engine) which uses a different syntax with indentation and spaces.


2 Answers

Declare a static directory:

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

<link rel='stylesheet' href='/style.css' />
like image 86
chovy Avatar answered Sep 24 '22 13:09

chovy


in app.js:

 you must first declare static directory 

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

in ejs file :

<link rel='stylesheet' href='/styles/style.css' />
like image 38
ahmed hamdy Avatar answered Sep 21 '22 13:09

ahmed hamdy