Search code examples
node.jsexpressswig-template

Rendering Static Files With Swig


I'm trying to develop a Blog with NodeJS. I found a nice HTML blog theme, and put all files to views folder. This is the content of app.js

var express = require('express'),
    app = express(),
    cons = require('consolidate');

app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
//app.use(express.static(__dirname + '/views'));
app.use(express.bodyParser());
// I'm using Express 3, not 4.
app.use(app.router);

app.get('/', function(req,res){
    res.render('index', {menu_items:[{"link":"#","text":"TXT"},{"link":"#","text":"TXT"}]});
});


app.listen(3000);

This code is rendering index.html and also rendering menu_items in index.html . But it's not rendering static files like css and js.

enter image description here

To render them I'm commenting out app.use(express.static(__dirname + '/views')); line. This time it's rendering static files but not rendering menu_items variable in index.html . enter image description here

You can see all files in this repository. Can you tell me what's I'm missing?

** UPDATE 1 ** I've added these lines instead of that commented line

app.use('/css', express.static(__dirname + '/views/css'));
app.use('/img', express.static(__dirname + '/views/img'));
app.use('/js', express.static(__dirname + '/views/js'));

But I'm not sure if it's correct way to solve my problem.


Solution

  • when you put the route string as `'/', the pattern matches all url requests. And the handlers registered after '/' gets ignored. So, You need to add the lines first,

    app.use('/css', express.static(__dirname + '/views/css'));
    app.use('/img', express.static(__dirname + '/views/img'));
    app.use('/js', express.static(__dirname + '/views/js'));
    

    and then add this router at the end,

    app.get('/', function(req,res){
    res.render('index', {menu_items:[{"link":"#","text":"TXT"},{"link":"#","text":"TXT"}]});
    

    });