Prettifying HTML

Here’s the HTML for the b8r “fiddle” component. It’s fairly tidy, but you don’t need to look far for some indentation inconsistencies, and many of the lines are rather long.

Given that it is the bedrock of the web, it’s surprisingly hard to find tools for improving HTML. It took me quite some time to find an HTML linter that even worked, and it doesn’t do a lot. Recently, I went looking for an HTML prettifier, and basically ran into a blank wall.

Since I pride myself on lazy programming, I decided to leverage the browser to deal with HTML parsing, and then use the parsed structure to generate HTML using consistent rules.

And here’s the output of html-render.js. It had no trouble keeping lines within 80 characters, and it’s done some nice things like sorting attributes into (my ideal) order: alphabetical, except with data-list, data-bind, and data-event up the top, and in that order. There aren’t any in this example, but multiple data and event bindings in a single tag are split into separate lines and consistently indented as well.

The result is a small library of about 240loc, half of which is documentation and an example (the example will grab a component by name and render its view HTML, and is what I took these screen caps from).

Anyway, I have plans for this little library. To start with, I want to render the HTML in my b8r components much more nicely and consistently. Also, by processing the HTML this way, I can do my own linting, including detecting broken bindings.

Ultimately, it means that HTML (and CSS) can simply be turned into pure data within components, eliminating inline-HTML (and CSS) from component code.