lib/nanoc3/helpers/html_escape.rb in nanoc3-3.2.0a1 vs lib/nanoc3/helpers/html_escape.rb in nanoc3-3.2.0a2
- old
+ new
@@ -3,20 +3,50 @@
module Nanoc3::Helpers
# Contains functionality for HTML-escaping strings.
module HTMLEscape
- # Returns the HTML-escaped representation of the given string. Only `&`,
- # `<`, `>` and `"` are escaped.
+ require 'nanoc3/helpers/capturing'
+ include Nanoc3::Helpers::Capturing
+
+ # Returns the HTML-escaped representation of the given string or the given
+ # block. Only `&`, `<`, `>` and `"` are escaped. When given a block, the
+ # contents of the block will be escaped and appended to the output buffer,
+ # `_erbout`.
#
+ # @example Escaping a string
+ #
+ # h('<br>')
+ # # => '<br>'
+ #
+ # @example Escaping with a block
+ #
+ # <% h do %>
+ # <h1>Hello <em>world</em>!</h1>
+ # <% end %>
+ # # The buffer will now contain “<h1>Hello <em>world</em>!</h1>”
+ #
# @param [String] string The string to escape
#
# @return [String] The escaped string
- def html_escape(string)
- string.gsub('&', '&').
- gsub('<', '<').
- gsub('>', '>').
- gsub('"', '"')
+ def html_escape(string=nil, &block)
+ if block_given?
+ # Capture and escape block
+ data = capture(&block)
+ escaped_data = html_escape(data)
+
+ # Append filtered data to buffer
+ buffer = eval('_erbout', block.binding)
+ buffer << escaped_data
+ elsif string
+ string.gsub('&', '&').
+ gsub('<', '<').
+ gsub('>', '>').
+ gsub('"', '"')
+ else
+ raise RuntimeError, "The #html_escape or #h function needs either a " \
+ "string or a block to HTML-escape, but neither a string nor a block was given"
+ end
end
alias h html_escape
end