Soaring Seagull

MVC and NodeJS

So, I like MVC. (Model, View, Controller)

The “view” in MVC is one of the really cool pieces; it allows you to quickly and easily make a template that you can apply “data” to at will. It allows for a dynamic website without needing to build extra pages. It can also help SEO and a number of other things.

So, lets start by having you create a new folder called “Template Project”.  Then, inside that, you’ll need to create a file named “app.js” and a  sub folder named “Template”. In the Template folder, create a file named “hello.html”.

First, we’ll make the hello.html file, as it is the easiest.

<h1>Hello, {{name}}</h1>
<h2>This is a basic page.</h2>
<p>Sometimes, when you're building a basic page, you want to apply styles. We're not going to be doing that here because it would detract from the purpose of showing you how templates work.</p>
<p>However, {{name}}, we did feel that it was important to use multiple lines of text to help hit home how easy it is to change things.</p>
<hr/>
<p>So, to that end we've got a few paragraphs of information. Now, we need to do something extra with it. So, below you'll see some fields. They will take on certain data aspects.</p>
<ul>
  <li>Name: {{name}}</li>
  <li>Age: {{age}}</li>
  <li>Height: {{height}}</li>
  <li>Hair Color: {{hair}}</li>
  <li>Eye Color: {{eye}}</li>
</ul>

Note that we use {{name}}, {{age}}, {{height}}, {{hair}}, and {{eye}}. These are the parts that will be the “template”. Each of these will be replaced by something from the URL. (Now, normally I wouldn’t recommend using URL parameters in the webpage, but this is just an example to show how these work. Education purposes only.)

So, next we’ve got to write the JS that will use the template.

var express = require('express');
var app = express();
var engines = require('consolidate');

We’re going to be using express to handle most of the heavy lifting when it comes to the web framework. We’re also using something called Consolidate, which is going to allow us to access the template engine of our choice. In this case, we’re going to be using nunjucks, because it is simple and straight forward. There are plenty of other template engines to work with, though – find what works best for your project.

So, lets go ahead and call our engine.

app.engine('html', engines.nunjucks);
app.set('view engine', 'html');
app.set('views', __dirname + '/template');

engines.nunjucks tells our app what template system we want to use. app.set(‘view engine’, ‘html’); is setting our default extension to HTML. So when we call “hello”, this will redirect the application to ‘hello.html’. app.set(‘views’, __dirname + ‘/template’) sets the folder for where the application’s views should be stored. In this case, we use __dirname (the name of the directory our application is running in) + ‘/template’ because we’re storing ‘hello.html’ in the ‘template’ folder.

Now lets set it up to display something.

app.get('/', function(req, res) {
  res.render('hello', {'name' : 'Unknown', 'age' : 'Unknown', 'height': 'Unknown', 'hair': 'Unknown', 'eye': 'Unknown'});
})

So, whenever someone goes to the base URL, we want to do something. The ‘/’ sets that for us. We’re going to add some parameters to a URL later, but at this point, we want to make sure people coming to the base site are getting something when they arrive. res.render is our response. res.render tells the application to render something from a view. The first parameter, ‘hello’, is the view that should be returned. (Because of our prior app.set(‘views’, __dirname + ‘/template’) setting, it knows to look inside ‘/template’ for a file named hello. Because we used app.set(‘view engine’, ‘html’), it knows it should look for hello.html, not just “hello”.

The second parameter is a JSON object with our template variables. Since we don’t know anything about the person, all of the fields are set to “unknown”.

Lets set it up to get some information from the URL to fill in some of that information:

app.get('/:name/:age/:height/:hair/:eye', function(req, res){
  res.render('hello', {'name' : req.params.name, 'age' : req.params.age, 'height' : req.params.height, 'hair' : req.params.hair, 'eye' : req.params.eye });
  console.log(req.params);
})

Now, we’re setting this up to take ‘name’, ‘age’, ‘height’, ‘hair’, and ‘eye’ from the URL. The :name, for example, gives us a parameter of “name” that we can access through req.params.name. Each of the variables is accessible this way, and we can build our JSON object just like we did before, only replacing ‘unknown’ with the parameter name.

Now we don’t want people to just hit a non-existent page and get nothing back, so we’ll throw a quick 404 response on:

app.use(function(req,res){
  res.sendStatus(404);
})

And now lets set the server up to run:

var server = app.listen(3000, 'localhost', function(){
  var port = server.address().port;
  console.log('localhost listening on port %s', port);
})

Now, you’ll need to open command prompt, and change your directory to your “Template Project” folder. We need to use NPM to install a few things so that this works. The commands are as below, assuming you put the folder on your Desktop!

cd desktop\template project
npm install express
npm install consolidate
npm install nunjucks
node app.js

When you run the application, you should get our webpage. Then try this URL:

http://localhost:3000/James/29/70%20inches/brown/green

You should get a webpage that looks like this:

Template Webpage

There you have it. You’ve built your first template webpage using NodeJS!

spacer

One comment on “MVC and NodeJS

  1. Pingback: Employee Website – a NodeJS example – Entwined Studios

Leave a reply