Included Modules

Haml::Helpers

This module contains various helpful methods to make it easier to do various tasks. {Haml::Helpers} is automatically included in the context that a Haml template is parsed in, so all these methods are at your disposal from within the template.

Constants

HTML_ESCAPE

Characters that need to be escaped to HTML entities from user input

Public Class Methods

action_view?() click to toggle source

@return [Boolean] Whether or not ActionView is loaded

    # File lib/haml/helpers.rb, line 53
53:     def self.action_view?
54:       @@action_view_defined
55:     end

Public Instance Methods

block_is_haml?(block) click to toggle source

Returns whether or not `block` is defined directly in a Haml template.

@param block [Proc] A Ruby block @return [Boolean] Whether or not `block` is defined directly in a Haml template

     # File lib/haml/helpers.rb, line 542
542:     def block_is_haml?(block)
543:       eval('_hamlout', block.binding)
544:       true
545:     rescue
546:       false
547:     end
capture_haml(*args, &block) click to toggle source

Captures the result of a block of Haml code, gets rid of the excess indentation, and returns it as a string. For example, after the following,

    .foo
      * foo = capture_haml(13) do |a|
        %p= a

the local variable `foo` would be assigned to `”

13

n“`.

@param args [Array] Arguments to pass into the block @yield [args] A block of Haml code that will be converted to a string @yieldparam args [Array] `args`

     # File lib/haml/helpers.rb, line 339
339:     def capture_haml(*args, &block)
340:       buffer = eval('_hamlout', block.binding) rescue haml_buffer
341:       with_haml_buffer(buffer) do
342:         position = haml_buffer.buffer.length
343: 
344:         haml_buffer.capture_position = position
345:         block.call(*args)
346: 
347:         captured = haml_buffer.buffer.slice!(position..1)
348:         return captured if haml_buffer.options[:ugly]
349:         captured = captured.split(/^/)
350: 
351:         min_tabs = nil
352:         captured.each do |line|
353:           tabs = line.index(/[^ ]/) || line.length
354:           min_tabs ||= tabs
355:           min_tabs = min_tabs > tabs ? tabs : min_tabs
356:         end
357: 
358:         captured.map do |line|
359:           line[min_tabs..1]
360:         end.join
361:       end
362:     ensure
363:       haml_buffer.capture_position = nil
364:     end
escape_once(text) click to toggle source

Escapes HTML entities in `text`, but without escaping an ampersand that is already part of an escaped entity.

@param text [String] The string to sanitize @return [String] The sanitized string

     # File lib/haml/helpers.rb, line 521
521:     def escape_once(text)
522:       Haml::Util.silence_warnings do
523:         text.to_s.gsub(/[\"><]|&(?!(?:[a-zA-Z]+|(#\d+));)/) {|s| HTML_ESCAPE[s]}
524:       end
525:     end
find_and_preserve(input = nil, tags = haml_buffer.options[:preserve], &block) click to toggle source

Uses {#preserve} to convert any newlines inside whitespace-sensitive tags into the HTML entities for endlines.

@param tags [Array] Tags that should have newlines escaped

@overload find_and_preserve(input, tags = haml_buffer.options[:preserve])

  Escapes newlines within a string.

  @param input [String] The string within which to escape newlines

@overload find_and_preserve(tags = haml_buffer.options[:preserve])

  Escapes newlines within a block of Haml code.

  @yield The block within which to escape newlines
     # File lib/haml/helpers.rb, line 108
108:     def find_and_preserve(input = nil, tags = haml_buffer.options[:preserve], &block)
109:       return find_and_preserve(capture_haml(&block), input || tags) if block
110:       re = /<(#{tags.map(&Regexp.method(:escape)).join('|')})([^>]*)>(.*?)(<\/\11>>)/m
111:       input.to_s.gsub(re) do |s|
112:         s =~ re # Can't rely on $1, etc. existing since Rails' SafeBuffer#gsub is incompatible
113:         "<#{$1}#{$2}>#{preserve($3)}</#{$1}>"
114:       end
115:     end
flatten(input = nil, &block) click to toggle source
Alias for: preserve
haml_concat(text = "") click to toggle source

Outputs text directly to the Haml buffer, with the proper indentation.

@param text [#] The text to output

     # File lib/haml/helpers.rb, line 369
369:     def haml_concat(text = "")
370:       unless haml_buffer.options[:ugly] || haml_indent == 0
371:         haml_buffer.buffer << haml_indent <<
372:           text.to_s.gsub("\n", "\n" + haml_indent) << "\n"
373:       else
374:         haml_buffer.buffer << text.to_s << "\n"
375:       end
376:       ErrorReturn.new("haml_concat")
377:     end
haml_indent() click to toggle source

@return [String] The indentation string for the current line

     # File lib/haml/helpers.rb, line 380
380:     def haml_indent
381:       '  ' * haml_buffer.tabulation
382:     end
haml_tag(name, *rest, &block) click to toggle source

Creates an HTML tag with the given name and optionally text and attributes. Can take a block that will run between the opening and closing tags. If the block is a Haml block or outputs text using {#haml_concat}, the text will be properly indented.

`name` can be a string using the standard Haml class/id shorthand (e.g. “span#.bar”, “#“). Just like standard Haml tags, these class and id values will be merged with manually-specified attributes.

`flags` is a list of symbol flags like those that can be put at the end of a Haml tag (`:/`, `:<`, and `:>`). Currently, only `:/` and `:<` are supported.

`haml_tag` outputs directly to the buffer; its return value should not be used. If you need to get the results as a string, use {#capture_haml}.

For example,

    haml_tag :table do
      haml_tag :tr do
        haml_tag 'td.cell' do
          haml_tag :strong, "strong!"
          haml_concat "data"
        end
        haml_tag :td do
          haml_concat "more_data"
        end
      end
    end

outputs

    <table>
      <tr>
        <td class='cell'>
          <strong>
            strong!
          </strong>
          data
        </td>
        <td>
          more_data
        </td>
      </tr>
    </table>

@param name [#] The name of the tag @param flags [Array] Haml end-of-tag flags

@overload haml_tag(name, *flags, attributes = {})

  @yield The block of Haml code within the tag

@overload haml_tag(name, text, *flags, attributes = {})

  @param text [#to_s] The text within the tag
     # File lib/haml/helpers.rb, line 441
441:     def haml_tag(name, *rest, &block)
442:       ret = ErrorReturn.new("haml_tag")
443: 
444:       text = rest.shift.to_s unless [Symbol, Hash, NilClass].any? {|t| rest.first.is_a? t}
445:       flags = []
446:       flags << rest.shift while rest.first.is_a? Symbol
447:       attrs = Haml::Util.map_keys(rest.shift || {}) {|key| key.to_s}
448:       name, attrs = merge_name_and_attributes(name.to_s, attrs)
449: 
450:       attributes = Haml::Compiler.build_attributes(haml_buffer.html?,
451:         haml_buffer.options[:attr_wrapper],
452:         haml_buffer.options[:escape_attrs],
453:         attrs)
454: 
455:       if text.nil? && block.nil? && (haml_buffer.options[:autoclose].include?(name) || flags.include?(:/))
456:         haml_concat "<#{name}#{attributes} />"
457:         return ret
458:       end
459: 
460:       if flags.include?(:/)
461:         raise Error.new("Self-closing tags can't have content.") if text
462:         raise Error.new("Illegal nesting: nesting within a self-closing tag is illegal.") if block
463:       end
464: 
465:       tag = "<#{name}#{attributes}>"
466:       if block.nil?
467:         text = text.to_s
468:         if text.include?("\n")
469:           haml_concat tag
470:           tab_up
471:           haml_concat text
472:           tab_down
473:           haml_concat "</#{name}>"
474:         else
475:           tag << text << "</#{name}>"
476:           haml_concat tag
477:         end
478:         return ret
479:       end
480: 
481:       if text
482:         raise Error.new("Illegal nesting: content can't be both given to haml_tag :#{name} and nested within it.")
483:       end
484: 
485:       if flags.include?(:<)
486:         tag << capture_haml(&block).strip << "</#{name}>"
487:         haml_concat tag
488:         return ret
489:       end
490: 
491:       haml_concat tag
492:       tab_up
493:       block.call
494:       tab_down
495:       haml_concat "</#{name}>"
496: 
497:       ret
498:     end
html_attrs(lang = 'en-US') click to toggle source

Returns a hash containing default assignments for the `xmlns`, `lang`, and `xml:lang` attributes of the `html` HTML element. For example,

    %html{html_attrs}

becomes

    <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en-US' lang='en-US'>

@param lang [String] The value of `xml:lang` and `lang` @return [{# => String}] The attribute hash

     # File lib/haml/helpers.rb, line 198
198:     def html_attrs(lang = 'en-US')
199:       {:xmlns => "http://www.w3.org/1999/xhtml", 'xml:lang' => lang, :lang => lang}
200:     end
html_escape(text) click to toggle source

Returns a copy of `text` with ampersands, angle brackets and quotes escaped into HTML entities.

Note that if ActionView is loaded and XSS protection is enabled (as is the default for Rails 3.0+, and optional for version 2.3.5+), this won’t escape text declared as “safe”.

@param text [String] The string to sanitize @return [String] The sanitized string

     # File lib/haml/helpers.rb, line 512
512:     def html_escape(text)
513:       Haml::Util.silence_warnings {text.to_s.gsub(/[\"><&]/) {|s| HTML_ESCAPE[s]}}
514:     end
init_haml_helpers() click to toggle source

Note: this does *not* need to be called when using Haml helpers normally in Rails.

Initializes the current object as though it were in the same context as a normal ActionView instance using Haml. This is useful if you want to use the helpers in a context other than the normal setup with ActionView. For example:

    context = Object.new
    class << context
      include Haml::Helpers
    end
    context.init_haml_helpers
    context.haml_tag :p, "Stuff"
    # File lib/haml/helpers.rb, line 73
73:     def init_haml_helpers
74:       @haml_buffer = Haml::Buffer.new(@haml_buffer, Haml::Engine.new('').send(:options_for_buffer))
75:       nil
76:     end
is_haml?() click to toggle source

Returns whether or not the current template is a Haml template.

This function, unlike other {Haml::Helpers} functions, also works in other `ActionView` templates, where it will always return false.

@return [Boolean] Whether or not the current template is a Haml template

     # File lib/haml/helpers.rb, line 534
534:     def is_haml?
535:       !@haml_buffer.nil? && @haml_buffer.active?
536:     end
list_of(enum, &block) click to toggle source

Takes an `Enumerable` object and a block and iterates over the enum, yielding each element to a Haml block and putting the result into `

  • ` elements. This creates a list of the results of the block. For example:

        = list_of([['hello'], ['yall']]) do |i|
          = i[0]
    

    Produces:

        <li>hello</li>
        <li>yall</li>
    

    And

        = list_of({:title => 'All the stuff', :description => 'A book about all the stuff.'}) do |key, val|
          %h3= key.humanize
          %p= val
    

    Produces:

        <li>
          <h3>Title</h3>
          <p>All the stuff</p>
        </li>
        <li>
          <h3>Description</h3>
          <p>A book about all the stuff.</p>
        </li>
    

    @param enum [Enumerable] The list of objects to iterate over @yield [item] A block which contains Haml code that goes within list items @yieldparam item An element of `enum`

         # File lib/haml/helpers.rb, line 170
    170:     def list_of(enum, &block)
    171:       to_return = enum.collect do |i|
    172:         result = capture_haml(i, &block)
    173: 
    174:         if result.count("\n") > 1
    175:           result = result.gsub("\n", "\n  ")
    176:           result = "\n  #{result.strip}\n"
    177:         else
    178:           result = result.strip
    179:         end
    180: 
    181:         "<li>#{result}</li>"
    182:       end
    183:       to_return.join("\n")
    184:     end
  • non_haml() click to toggle source

    Runs a block of code in a non-Haml context (i.e. {#is_haml?} will return false).

    This is mainly useful for rendering sub-templates such as partials in a non-Haml language, particularly where helpers may behave differently when run from Haml.

    Note that this is automatically applied to Rails partials.

    @yield A block which won’t register as Haml

        # File lib/haml/helpers.rb, line 87
    87:     def non_haml
    88:       was_active = @haml_buffer.active?
    89:       @haml_buffer.active = false
    90:       yield
    91:     ensure
    92:       @haml_buffer.active = was_active
    93:     end
    precede(str, &block) click to toggle source

    Prepends a string to the beginning of a Haml block, with no whitespace between. For example:

        = precede '*' do
          %span.small Not really
    

    Produces:

        *<span class='small'>Not really</span>
    

    @param str [String] The string to add before the Haml @yield A block of Haml to prepend to

         # File lib/haml/helpers.rb, line 302
    302:     def precede(str, &block)
    303:       "#{str}#{capture_haml(&block).chomp}\n"
    304:     end
    preserve(input = nil, &block) click to toggle source

    Takes any string, finds all the newlines, and converts them to HTML entities so they’ll render correctly in whitespace-sensitive tags without screwing up the indentation.

    @overload perserve(input)

      Escapes newlines within a string.
    
      @param input [String] The string within which to escape all newlines
    

    @overload perserve

      Escapes newlines within a block of Haml code.
    
      @yield The block within which to escape newlines
         # File lib/haml/helpers.rb, line 129
    129:     def preserve(input = nil, &block)
    130:       return preserve(capture_haml(&block)) if block
    131:       input.to_s.chomp("\n").gsub(/\n/, '&#x000A;').gsub(/\r/, '')
    132:     end
    Also aliased as: flatten
    succeed(str, &block) click to toggle source

    Appends a string to the end of a Haml block, with no whitespace between. For example:

        click
        = succeed '.' do
          %a{:href=>"thing"} here
    

    Produces:

        click
        <a href='thing'>here</a>.
    

    @param str [String] The string to add after the Haml @yield A block of Haml to append to

         # File lib/haml/helpers.rb, line 321
    321:     def succeed(str, &block)
    322:       "#{capture_haml(&block).chomp}#{str}\n"
    323:     end
    surround(front, back = front, &block) click to toggle source

    Surrounds a block of Haml code with strings, with no whitespace in between. For example:

        = surround '(', ')' do
          %a{:href => "food"} chicken
    

    Produces:

        (<a href='food'>chicken</a>)
    

    and

        = surround '*' do
          %strong angry
    

    Produces:

        *<strong>angry</strong>*
    

    @param front [String] The string to add before the Haml @param back [String] The string to add after the Haml @yield A block of Haml to surround

         # File lib/haml/helpers.rb, line 283
    283:     def surround(front, back = front, &block)
    284:       output = capture_haml(&block)
    285: 
    286:       "#{front}#{output.chomp}#{back}\n"
    287:     end
    tab_down(i = 1) click to toggle source

    Decrements the number of tabs the buffer automatically adds to the lines of the template.

    @param i [Fixnum] The number of tabs by which to decrease the indentation @see #

         # File lib/haml/helpers.rb, line 229
    229:     def tab_down(i = 1)
    230:       haml_buffer.tabulation -= i
    231:     end
    tab_up(i = 1) click to toggle source

    Increments the number of tabs the buffer automatically adds to the lines of the template. For example:

        %h1 foo
        * tab_up
        %p bar
        * tab_down
        %strong baz
    

    Produces:

        <h1>foo</h1>
          <p>bar</p>
        <strong>baz</strong>
    

    @param i [Fixnum] The number of tabs by which to increase the indentation @see #

         # File lib/haml/helpers.rb, line 220
    220:     def tab_up(i = 1)
    221:       haml_buffer.tabulation += i
    222:     end
    with_tabs(i) click to toggle source

    Sets the number of tabs the buffer automatically adds to the lines of the template, but only for the duration of the block. For example:

        %h1 foo
        * with_tabs(2) do
          %p bar
        %strong baz
    

    Produces:

        <h1>foo</h1>
            <p>bar</p>
        <strong>baz</strong>
    

    @param i [Fixnum] The number of tabs to use @yield A block in which the indentation will be `i` spaces

         # File lib/haml/helpers.rb, line 252
    252:     def with_tabs(i)
    253:       old_tabs = haml_buffer.tabulation
    254:       haml_buffer.tabulation = i
    255:       yield
    256:     ensure
    257:       haml_buffer.tabulation = old_tabs
    258:     end

    Private Instance Methods

    haml_bind_proc(&proc) click to toggle source

    Gives a proc the same local `_hamlout` and `_erbout` variables that the current template has.

    @param proc [#] The proc to bind @return [Proc] A new proc with the new variables bound

         # File lib/haml/helpers.rb, line 588
    588:     def haml_bind_proc(&proc)
    589:       _hamlout = haml_buffer
    590:       _erbout = _hamlout.buffer
    591:       proc { |*args| proc.call(*args) }
    592:     end
    haml_buffer() click to toggle source

    The current {Haml::Buffer} object.

    @return [Haml::Buffer]

         # File lib/haml/helpers.rb, line 579
    579:     def haml_buffer
    580:       @haml_buffer
    581:     end
    merge_name_and_attributes(name, attributes_hash = {}) click to toggle source

    Parses the tag name used for {#haml_tag} and merges it with the Ruby attributes hash.

         # File lib/haml/helpers.rb, line 553
    553:     def merge_name_and_attributes(name, attributes_hash = {})
    554:       # skip merging if no ids or classes found in name
    555:       return name, attributes_hash unless name =~ /^(.+?)?([\.#].*)$/
    556: 
    557:       return $1 || "div", Buffer.merge_attrs(
    558:         Haml::Parser.parse_class_and_id($2), attributes_hash)
    559:     end
    with_haml_buffer(buffer) click to toggle source

    Runs a block of code with the given buffer as the currently active buffer.

    @param buffer [Haml::Buffer] The Haml buffer to use temporarily @yield A block in which the given buffer should be used

         # File lib/haml/helpers.rb, line 565
    565:     def with_haml_buffer(buffer)
    566:       @haml_buffer, old_buffer = buffer, @haml_buffer
    567:       old_buffer.active, old_was_active = false, old_buffer.active? if old_buffer
    568:       @haml_buffer.active, was_active = true, @haml_buffer.active?
    569:       yield
    570:     ensure
    571:       @haml_buffer.active = was_active
    572:       old_buffer.active = old_was_active if old_buffer
    573:       @haml_buffer = old_buffer
    574:     end

    Disabled; run with --debug to generate this.

    [Validate]

    Generated with the Darkfish Rdoc Generator 1.1.6.