Tag Archives: node.js

Underscore templates with Node.js

A while back I wrote a post about using underscore templates and how they can help to organize your application’s markup. Today we are going to talk about how we can take this one step further and use underscore templates within a node.js application to write a simple backbone generator.

Getting underscore

First thing we need to do is get underscore. NPM (Node package manager) will be our friend here. If npm is installed, we can get underscore simply by typing the following from the command line.

Creating our node.js program

First thing we need to do is create our node program. We will save this as file called bb.js. Inside bb.js add the code below. To get started we are requiring underscore, the node file system, and defining our template file.

Next, we need to make a function in bb.js that will generate our file based on the backbone-view template. (Which we will create later)

The template will be run from the command line using

Create File

The first thing createFile() does is look at the arguments passed to node. Since our command is going to be “node bb <view_name>” the view name will be the 3rd argument from process.argv. Process.argv is just an array containing the command line arguments. Next, if a view name was passed in we will setup a file path based on the current working directory and the view name.
Ex. path/to/current/directory/view_name.js.

Line 9 will use the node file system to read in our template file and convert it to a string. Finally, we will apply the _.template function using our templateFile string and view name as parameters. We will then write out the result to a file using the node file system.

Our backbone-view.js template file

As you can see the backbone view template is pretty simple. It takes the view name that was passed in and applies it in several different spots.

And that’s it. It is pretty easy to write a little node.js and underscore program to help with simple tasks such as writing out template files. Obviously this is a very simple example. In the next post we will combine this general idea with cli ( a command line tool for node ) to make a more powerful interface for generating files and folders with node.