Module: Nanoc::Helpers::HTMLEscape

Includes:
Capturing
Included in:
LinkTo, Tagging
Defined in:
lib/nanoc/helpers/html_escape.rb

Overview

Contains functionality for HTML-escaping strings.

Instance Method Summary (collapse)

Methods included from Capturing

#capture, #content_for

Instance Method Details

- (String) html_escape(string = nil, &block) Also known as: h

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.

Examples:

Escaping a string


h('<br>')
# => '&lt;br&gt;'

Escaping with a block


<% h do %>
  <h1>Hello <em>world</em>!</h1>
<% end %>
# The buffer will now contain “&lt;h1&gt;Hello &lt;em&gt;world&lt;/em&gt;!&lt;/h1&gt;”

Parameters:

  • string (String) (defaults to: nil)

    The string to escape

Returns:

  • (String)

    The escaped string



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/nanoc/helpers/html_escape.rb', line 29

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('&', '&amp;')
      .gsub('<', '&lt;')
      .gsub('>', '&gt;')
      .gsub('"', '&quot;')
  else
    raise '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