Skip to content

Commit

Permalink
Add information about custom HTML formatters to README (#1415)
Browse files Browse the repository at this point in the history
Rouge users are occasionally confused by the manner in which custom HTML
formatters can be written for Rouge. This commit adds practical
information about this topic to the README.
  • Loading branch information
jneen committed Feb 5, 2020
1 parent 5896d00 commit 086630e
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions README.md
Expand Up @@ -117,6 +117,55 @@ The built-in formatters are:
highlighted text for use in the terminal. `theme` must be an instance of
`Rouge::Theme`, or a `Hash` structure with `:theme` entry.

#### Writing your own HTML formatter

If the above formatters are not sufficient, and you wish to customize the layout
of the HTML document, we suggest writing your own HTML formatter. This can be
accomplished by subclassing `Rouge::Formatters::HTML` and overriding specific
methods:

``` ruby
class MyFormatter < Rouge::Formatters::HTML

# this is the main entry method. override this to customize the behavior of
# the HTML blob as a whole. it should receive an Enumerable of (token, value)
# pairs and yield out fragments of the resulting html string. see the docs
# for the methods available on Token.
def stream(tokens, &block)
yield "<div class='my-outer-div'>"

tokens.each do |token, value|
# for every token in the output, we render a span
yield span(token, value)
end

yield "</div>"
end

# or, if you need linewise processing, try:
def stream(tokens, &block)
token_lines(tokens).each do |line_tokens|
yield "<div class='my-cool-line'>"
line_tokens.each do |token, value|
yield span(token, value)
end
yield "</div>"
end
end

# Override this method to control how individual spans are rendered.
# The value `safe_value` will already be HTML-escaped.
def safe_span(token, safe_value)
# in this case, "text" tokens don't get surrounded by a span
if token == Token::Tokens::Text
safe_value
else
"<span class=\"#{token.shortname}\">#{safe_value}</span>"
end
end
end
```

### Lexer Options

* `debug: false` will print a trace of the lex on stdout.
Expand Down

0 comments on commit 086630e

Please sign in to comment.