How can I get Express to output nicely formatted HTML?

To "pretty-format" html output in Jade/Express:

app.set('view options', { pretty: true });

In your main app.js or what is in it's place:

Express 4.x

if (app.get('env') === 'development') {
  app.locals.pretty = true;
}

Express 3.x

app.configure('development', function(){
  app.use(express.errorHandler());
  app.locals.pretty = true;
});

Express 2.x

app.configure('development', function(){
  app.use(express.errorHandler());
  app.set('view options', { pretty: true });
});

I put the pretty print in development because you'll want more efficiency with the 'ugly' in production. Make sure to set environment variable NODE_ENV=production when you're deploying in production. This can be done with an sh script you use in the 'script' field of package.json and executed to start.

Express 3 changed this because:

The "view options" setting is no longer necessary, app.locals are the local variables merged with res.render()'s, so [app.locals.pretty = true is the same as passing res.render(view, { pretty: true }).


In express 4.x, add this to your app.js:

if (app.get('env') === 'development') {
  app.locals.pretty = true;
}

There is a "pretty" option in Jade itself:

var jade = require("jade");

var jade_string = [
    "!!! 5",
    "html",
    "    body",
    "        #foo  I am a foo div!"
].join("\n");

var fn = jade.compile(jade_string, { pretty: true });
console.log( fn() );

...gets you this:

<!DOCTYPE html>
<html>
  <body>
    <div id="foo">I am a foo div!
    </div>
  </body>
</html>

I doesn't seem to be very sophisticated but for what I'm after -- the ability to actually debug the HTML my views produce -- it's just fine.