Created
February 15, 2013 04:03
-
-
Save geek0x23/4958515 to your computer and use it in GitHub Desktop.
So I wanted to get connect-flash messages to display in my dust templates in Express 3. This feels a bit hacky, but it's the best I could come up with to make things truly dust-friendly and keep my templates clean.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// hook up connect-flash | |
app.use(require("connect-flash")()); | |
// now hook up middleware that plays nicely with connect-flash and dust.js | |
app.use(function(req, res, next) { | |
// dust.js will pass arguments to this function, so we can't use bind | |
// or a simple proxy because connect-flash will think we're adding a | |
// message instead of retrieving them | |
res.locals.flash = function() { | |
var result = req.flash(), prop, messages = [], count; | |
// if we have no flash messages, just exit cleanly. | |
if (!Object.keys(result).length) { return undefined; } | |
// if we do have flash messages, each message type has | |
// a property in the "result" object, so we loop through | |
// the properties here | |
for (prop in result) { | |
// make sure the property belongs to us, and that we | |
// actually have some messages to show. | |
if (result.hasOwnProperty(prop) && result[prop].length) { | |
for (count = 0; count < result[prop].length; count += 1) { | |
// finally, push the message inside a simple object, so | |
// we can use a single section in the dust template. | |
messages.push({ "type": prop, "msg": result[prop][count] }); | |
} | |
} | |
} | |
// all done, we should have a nice, friendly array that | |
// dust.js can play with | |
return messages; | |
}; | |
next(); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>Sample app</title> | |
</head> | |
<body> | |
<!-- all that so we could have a single-line flash renderer :) --> | |
{#flash}<div class="flash {type}">{msg}</div>{/flash} | |
<p>You should see some flash messages</p> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment