Sometimes you may find useful to generate content dynamically. Maybe you’re going to read some configuration file, or maybe you just want to define some helpers. Kitabu has support for ERb files; all you need to do is naming your text file as .erb
.
On the previous chapter, we listed all supported Rouge lexers. To do that, I created a helper that looks like this:
module Kitabu
module Helpers
def lexers_list
buffer = '<ul class="lexers">'
Rouge::Lexers.constants.each do |const|
lexer = Rouge::Lexers.const_get(const)
begin
title = lexer.title
tag = lexer.tag
description = lexer.desc
rescue Exception => e
next
end
buffer << '<li>'
buffer << "<strong>#{title}</strong> "
buffer << "<code>#{tag}</code><br>"
buffer << "<span>#{description}</span>"
buffer << '</li>'
end
buffer << '</ul>'
buffer
end
end
end
To use it, I just needed to add <%= lexers_list %>
to my text file. This allows you to create anything you need!
Kitabu comes with some built-in helpers, such as note
. With this helper, you can create a note that generates a HTML structure, so you can easily style it. The syntax for using the note
helper is note(type, &block)
.
<% note do %>
Some text that will be parsed as Markdown.
<% end %>
By default, this will generate a <div class="note info">
tag, but you can use anything you want.
<% note :warning do %>
Some text that will be parsed as Markdown.
<% end %>
Check out the source for a sample on how to create block helpers like note
.
If you want to write a book about Rails, you’re likely to use lots of ERb tags. In this case, make sure you escape the and
markers as <% %>
and <%= %>
; otherwise you’ll have a syntax error.
<%%= Date.today %>