Sha256: 34d72448bd937fffbcc9ec2208003d9cc48d80ce1d509440973e720313c08122

Contents?: true

Size: 1.53 KB

Versions: 11

Compression:

Stored size: 1.53 KB

Contents

# encoding: utf-8

module Nanoc3::Helpers

  # Contains functionality for HTML-escaping strings.
  module HTMLEscape

    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>')
    #     # => '&lt;br&gt;'
    #
    # @example 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;”
    #
    # @param [String] string The string to escape
    #
    # @return [String] The escaped string
    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 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

end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
nanoc3-3.2.4 lib/nanoc3/helpers/html_escape.rb
nanoc3-3.2.3 lib/nanoc3/helpers/html_escape.rb
nanoc3-3.2.2 lib/nanoc3/helpers/html_escape.rb
nanoc3-3.2.1 lib/nanoc3/helpers/html_escape.rb
nanoc3-3.2.0 lib/nanoc3/helpers/html_escape.rb
nanoc3-3.2.0b3 lib/nanoc3/helpers/html_escape.rb
nanoc3-3.2.0b2 lib/nanoc3/helpers/html_escape.rb
nanoc3-3.2.0b1 lib/nanoc3/helpers/html_escape.rb
nanoc3-3.2.0a4 lib/nanoc3/helpers/html_escape.rb
nanoc3-3.2.0a3 lib/nanoc3/helpers/html_escape.rb
nanoc3-3.2.0a2 lib/nanoc3/helpers/html_escape.rb