public
Last active

Add stylesheets to Express layout dynamically

  • Download Gist
app.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
var express = require('express')
, app = express.createServer()
 
// Function to push formatted style
// paths onto our stylesheet variable
var addStyles = function(res, styles) {
styles.forEach(function(style){
res.app.settings['view options'].styles.push('/stylesheets/' + style + '.css')
})
return true
}
 
// 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.app.settings['view options'].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.render('home')
})
 
app.listen(3000)
layout.jade
Jade
1 2 3 4 5 6
!!!
html
head
- each style in styles
link(rel='stylesheet',type='text/css', href= style)
body!= body

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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.