Search code examples
node.jsdynamicexpressmiddlewarestylesheet

Dynamic stylesheets implemented by express middleware


I would like to be able to dynamically add a stylesheet from inside my routes to a global stylesheet array using express middleware.

I have come up with this gist https://gist.github.com/1375882 but each page refresh just continues to add the route's stylesheet list to the end of the array. How can I keep it from doing this?


Solution

  • I think this code will solve your problem:

    var express = require('express')
      , app = express.createServer()
    
    // Function to push formatted style
    // paths onto our stylesheet variable
    var addStyles = function(res, styles) {
      var temp = []
      styles.forEach(function(style){
        temp.push('/stylesheets/' + style + '.css')
      })
      temp = res.local('styles').concat(temp)
      res.local('styles', temp)
    }
    
    // Middleware that adds default styles
    var buildStyles = function(default_styles){
      var styles = []
      // format our default style paths
      default_styles.forEach(function(style){
        styles.push('/stylesheets/' + style + '.css')
      })
    
      return function(req, res, next) {
        res.local('styles', styles)
        next()
      }
    }
    
    // Configure our middleware
    app.configure(function(){
      app.use(express.static(__dirname + '/public'))
      app.set('views', __dirname + '/views')
      app.set('view engine', 'jade')
      // Call our custom middleware passing in
      // an array of global stylesheets to use
      app.use(buildStyles(['global']))
    })
    
    app.get('/',function(req, res){
      // Add forms.css and user/login.css stylesheet dynamically
      addStyles(res, ['forms','user/login'])
      res.json(res.local('styles'))
      //res.render('home')
    })
    
    app.listen(8080)