How can I get Express to output nicely formatted HTML?
Asked Answered
C

9

169

When using Express for Node.js, I noticed that it outputs the HTML code without any newline characters or tabs. Though it may be more efficient to download, it's not very readable during development.

How can I get Express to output nicely formatted HTML?

Clarkclarke answered 11/3, 2011 at 18:32 Comment(0)
P
317

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 }).

Poulter answered 4/8, 2012 at 23:41 Comment(9)
Please change the accepted answer to this as it's the right answer to date.Expiration
This worked, but I had to install a bunch of extra dependencies, namely promise, uglify-js, css and lexical-scope before it would run again (it would build, but crash on first request). I only added that one line.Moderate
How to do that in Express 4.x ?Interrupted
@AntonioSalvati try app.locals.pretty = trueAfroasian
This is an awesome answer, exactly what I was looking for. It's refreshing to see how this is done for different versions of Express. I've searched for other issues and found answers that didn't mention what version of Express it was for.Hitherto
Is this documented anywhere?Shipp
@Shipp there's a link in my answerPoulter
Yes, I see this... but it's not available in the Express 4 docs. At least I tried to google "pretty site:expressjs.com" to no availShipp
Great answer. But I see no reason to only pretty print in development mode. HTML is very small, especially for a Single Page App like angular. Plus there is no looping going on like in javascript, unless you put JS directly in your code (which you shouldn't unless absolutely necessary for setting a global JS var from the server, etc). Either way I always want to format my HTML so if there is some problem in production its apparent. Javascript however I would only pretty print for development.Lubricate
C
51

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

app.set('view options', { pretty: true });
Cantatrice answered 29/9, 2011 at 1:5 Comment(2)
Great solution! I wish it would match indent levels between layout/page too.Clarkclarke
Outdated. Express 3 works a little different, see post written by EhevuTov.Sagitta
R
7

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.

Radiolucent answered 6/2, 2012 at 1:20 Comment(2)
If debugging HTML is all you're after you could always just 'inspect' the HTML using the Webkit or Firebug inspector. That always generates a perfectly formatted DOM tree.Sarcoid
@Sarcoid true, but navigating through the tree is time consuming, when u can just scan the source quicker (sometimes)Expiration
R
7

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

if (app.get('env') === 'development') {
  app.locals.pretty = true;
}
Rochette answered 20/5, 2014 at 22:24 Comment(3)
Worked here - thanks! In my case I didn't have the 'env' var set. You can add it to the main .js file with this one line : process.env.NODE_ENV = 'development';Crain
Why are you giving this answer if other answers already are giving this solution?Nyctaginaceous
I was the first to give this answer, the other answer was updated afterwards.Rochette
C
4

If you are using the console to compile, then you can use something like this:

$ jade views/ --out html --pretty
Caputo answered 26/7, 2015 at 16:50 Comment(0)
M
1

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

app.locals.pretty = app.get('env') === 'development';
Mentalist answered 13/10, 2017 at 14:11 Comment(0)
S
0

Do you really need nicely formatted html? Even if you try to output something that looks nice in one editor, it can look weird in another. Granted, I don't know what you need the html for, but I'd try using the chrome development tools or firebug for Firefox. Those tools give you a good view of the DOM instead of the html.

If you really-really need nicely formatted html then try using EJS instead of jade. That would mean you'd have to format the html yourself though.

Subsistent answered 14/3, 2011 at 11:13 Comment(1)
I like ejs better now that I've worked with it for a while. I guess I'm just very particular about some things.Clarkclarke
A
0

you can use tidy

take for example this jade file:

foo.jade

h1 MyTitle

p
  a(class='button', href='/users/') show users

table
  thead
    tr
      th Name
      th Email
  tbody
    - var items = [{name:'Foo',email:'foo@bar'}, {name:'Bar',email:'bar@bar'}]
    - each item in items
      tr
        td= item.name
        td= item.email

now you can process it with node testjade.js foo.jade > output.html:

testjade.js

var jade = require('jade');
var jadeFile = process.argv[2];
jade.renderFile(__dirname + '/' + jadeFile, options, function(err, html){
    console.log(html);
});

will give you s.th. like:

output.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><title>My Title</title><link rel="stylesheet" href="/stylesheets/style.css"/><script type="text/javascript" src="../js/jquery-1.4.4.min.js"></script></head><body><div id="main"><div ><h1>MyTitle</h1><p><a href="/users/" class="button">show users</a></p><table><thead><tr><th>Name</th><th>Email</th></tr></thead><tbody><tr><td>Foo</td><td>foo@bar</td></tr><tr><td>Bar</td><td>bar@bar</td></tr></tbody></table></div></div></body></html

then running it through tidy with tidy -m output.html will result in:

output.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content=
"HTML Tidy for Linux (vers 25 March 2009), see www.w3.org" />
<title>My Title</title>
<link rel="stylesheet" href="/stylesheets/style.css" type=
"text/css" />
<script type="text/javascript" src="../js/jquery-1.4.4.min.js">
</script>
</head>
<body>
<div id="main">
<div>
<h1>MyTitle</h1>
<p><a href="/users/" class="button">show users</a></p>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>Foo</td>
<td>foo@bar</td>
</tr>
<tr>
<td>Bar</td>
<td>bar@bar</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
Antiphonal answered 27/4, 2011 at 9:26 Comment(0)
F
0

building off of oliver's suggestion, heres a quick and dirty way to view beautified html

1) download tidy

2) add this to your .bashrc

function tidyme() {
curl $1 | tidy -indent -quiet -output tidy.html ; open -a 'google chrome' tidy.html
}

3) run

$ tidyme localhost:3000/path

the open command only works on macs. hope that helps!

Ferromagnetism answered 11/6, 2011 at 20:32 Comment(1)
didn't know about the indent option...nice! I was using vim's built in formater.Antiphonal

© 2022 - 2024 — McMap. All rights reserved.