Skip to content

Instantly share code, notes, and snippets.

@PastorBones
Created November 18, 2011 08:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PastorBones/1375882 to your computer and use it in GitHub Desktop.
Save PastorBones/1375882 to your computer and use it in GitHub Desktop.
Add stylesheets to Express layout dynamically
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)
!!!
html
head
- each style in styles
link(rel='stylesheet',type='text/css', href= style)
body!= body
@alessioalex
Copy link

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment