A normaliser/beautifier for HTML that also understands embedded Ruby. Ideal for tidying up Rails templates.
- Normalises hard tabs to spaces (or vice versa)
- Removes trailing spaces
- Indents after opening HTML elements
- Outdents before closing elements
- Collapses multiple whitespace
- Indents after block-opening embedded Ruby (if, do etc.)
- Outdents before closing Ruby blocks
- Outdents elsif and then indents again
- Indents the left-hand margin of JavaScript and CSS blocks to match the indentation level of the code
To update files in-place:
$ htmlbeautifier file1.html.erb [file2.html.erb ...]or to operate on standard input and output:
$ htmlbeautifier < untidy.html.erb > formatted.html.erb| Option | Effect |
|---|---|
-t, --tab-stops NUMBER |
Number of spaces per indent (default 2) |
-T, --tab |
Indent using tabs |
-i, --indent-by NUMBER |
Indent the whole output by NUMBER steps (default 0) |
-b, --keep-blank-lines NUMBER |
Number of consecutive blank lines to keep (default 0) |
-e, --stop-on-errors |
Stop when invalid nesting is encountered, instead of carrying on |
-l, --lint-only |
Do not write anything; exit 1 listing the files that would be modified |
-v, --version |
Display the version and exit |
-h, --help |
Display the help message and exit |
--lint-only requires file arguments: it cannot report on standard input,
where there is no file to name. When files are given, each one is attempted
even if an earlier one fails, and the run exits 1 listing every failure.
Files are rewritten through a temporary file in the same directory, keeping the mode, the ownership and the symlink identity of the original.
require 'htmlbeautifier'
beautiful = HtmlBeautifier.beautify(untify_html_string)You can also specify how to indent (the default is two spaces):
beautiful = HtmlBeautifier.beautify(untidy_html_string, indent: "\t")The other options mirror the command-line flags. An unknown key raises
ArgumentError rather than being ignored:
| Option | Effect |
|---|---|
indent: |
String used for one indent level (default " ") |
initial_level: |
Indent the whole output by this many steps (default 0) |
keep_blank_lines: |
Number of consecutive blank lines to keep (default 0) |
stop_on_errors: |
Raise on invalid nesting instead of carrying on (default false) |
Both the document and its formatted form are held in memory, so a very large template needs roughly twice its own size.
This is a Ruby gem.
To install the command-line tool (you may need sudo):
$ gem install htmlbeautifierTo use the gem with Bundler, add to your Gemfile:
gem 'htmlbeautifier'See CHANGELOG.md for the list of changes in each release.
- Follow these guidelines when writing commit messages (briefly, the first line should begin with a capital letter, use the imperative mood, be no more than 50 characters, and not end with a period).
- Include tests.