Expressjs Static Blog
How can we define a static blog engine?
Here is a blog.js file that provides both for getting a set of entries as well as getting just one:
var entries = [
{"id":1, "title":"Hello World!", "body":"This is the body of my blog entry. Sooo exciting.", "published":"6/2/2013"},
{"id":2, "title":"Eggs for Breakfast", "body":"Today I had eggs for breakfast. Sooo exciting.", "published":"6/3/2013"},
{"id":3, "title":"Beer is Good", "body":"News Flash! Beer is awesome!", "published":"6/4/2013"},
{"id":4, "title":"Mean People Suck", "body":"People who are mean aren't nice or fun to hang around.", "published":"6/5/2013"},
{"id":5, "title":"I'm Leaving Technology X and You Care", "body":"Let me write some link bait about why I'm not using a particular technology anymore.", "published":"6/10/2013"},
{"id":6, "title":"Help My Kickstarter", "body":"I want a new XBox One. Please fund my Kickstarter.", "published":"6/12/2013"}];
exports.getBlogEntries = function() {
return entries;
}
exports.getBlogEntry = function(id) {
for(var i=0; i < entries.length; i++) {
if(entries[i].id == id) return entries[i];
}
}
and here is the updated app.js:
var express = require('express');
var app = express();
var hbs = require('hbs');
var blogEngine = require('./blog');
app.set('view engine', 'html');
app.engine('html', hbs.__express);
app.use(express.bodyParser());
app.get('/', function(req, res) {
res.render('index',{title:"My Blog", entries:blogEngine.getBlogEntries()});
});
app.get('/about', function(req, res) {
res.render('about', {title:"About Me"});
});
app.get('/article/:id', function(req, res) {
var entry = blogEngine.getBlogEntry(req.params.id);
res.render('article',{title:entry.title, blog:entry});
});
app.listen(3000);
So, we created the blog engine in blog.js file, and we've included it into our main app.js file using:
var blogEngine = require('./blog');
and we've updated the home page (in app.js) to list all blog entries:
app.get('/', function(req, res) {
res.render('index',{title:"My Blog", entries:blogEngine.getBlogEntries()});
});
Notice that we use blogEngine.getBlogEntries() and we've also actually use the Handlebars' render method with real templating stuff. We've also added a new route:
app.get('/article/:id', function(req, res) {
var entry = blogEngine.getBlogEntry(req.params.id);
res.render('article',{title:entry.title, blog:entry});
});
Notice that in the above code, we've use logEngine.getBlogEntry and req.params.id.
page revision: 0, last edited: 08 Oct 2015 05:55