Module Haml::Helpers
In: lib/haml/helpers.rb
lib/haml/helpers/xss_mods.rb
lib/haml/helpers/action_view_extensions.rb

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.

Methods

Included Modules

ActionViewExtensions

Classes and Modules

Module Haml::Helpers::ActionViewExtensions
Module Haml::Helpers::XssMods
Class Haml::Helpers::ErrorReturn

Constants

HTML_ESCAPE = { '&'=>'&amp;', '<'=>'&lt;', '>'=>'&gt;', '"'=>'&quot;', "'"=>'&#039;', }   Characters that need to be escaped to HTML entities from user input @private

Public Class methods

@return [Boolean] Whether or not ActionView is loaded

[Source]

    # File lib/haml/helpers.rb, line 60
60:     def self.action_view?
61:       @@action_view_defined
62:     end

Public Instance methods

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

[Source]

     # File lib/haml/helpers.rb, line 509
509:     def block_is_haml?(block)
510:       eval('_hamlout', block.binding)
511:       true
512:     rescue
513:       false
514:     end

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 `"<p>13</p>\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`

[Source]

     # File lib/haml/helpers.rb, line 317
317:     def capture_haml(*args, &block)
318:       buffer = eval('_hamlout', block.binding) rescue haml_buffer
319:       with_haml_buffer(buffer) do
320:         position = haml_buffer.buffer.length
321: 
322:         haml_buffer.capture_position = position
323:         block.call(*args)
324: 
325:         captured = haml_buffer.buffer.slice!(position..-1).split(/^/)
326: 
327:         min_tabs = nil
328:         captured.each do |line|
329:           tabs = line.index(/[^ ]/) || line.length
330:           min_tabs ||= tabs
331:           min_tabs = min_tabs > tabs ? tabs : min_tabs
332:         end
333: 
334:         captured.map do |line|
335:           line[min_tabs..-1]
336:         end.join
337:       end
338:     ensure
339:       haml_buffer.capture_position = nil
340:     end

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

[Source]

     # File lib/haml/helpers.rb, line 488
488:     def escape_once(text)
489:       Haml::Util.silence_warnings do
490:         text.to_s.gsub(/[\"><]|&(?!(?:[a-zA-Z]+|(#\d+));)/n) {|s| HTML_ESCAPE[s]}
491:       end
492:     end

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

@param tags [Array<String>] 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

[Source]

     # File lib/haml/helpers.rb, line 115
115:     def find_and_preserve(input = nil, tags = haml_buffer.options[:preserve], &block)
116:       return find_and_preserve(capture_haml(&block), input || tags) if block
117:       input.to_s.gsub(/<(#{tags.map(&Regexp.method(:escape)).join('|')})([^>]*)>(.*?)(<\/\1>)/im) do
118:         "<#{$1}#{$2}>#{preserve($3)}</#{$1}>"
119:       end
120:     end
flatten(input = nil, &block)

Alias for preserve

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

@param text [to_s] The text to output

[Source]

     # File lib/haml/helpers.rb, line 357
357:     def haml_concat(text = "")
358:       haml_buffer.buffer << haml_indent << text.to_s << "\n"
359:       ErrorReturn.new("haml_concat")
360:     end

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

[Source]

     # File lib/haml/helpers.rb, line 363
363:     def haml_indent
364:       '  ' * haml_buffer.tabulation
365:     end

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.

`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, {:class => '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 [to_s] The name of the tag @param flags [Array<Symbol>] 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

[Source]

     # File lib/haml/helpers.rb, line 419
419:     def haml_tag(name, *rest, &block)
420:       ret = ErrorReturn.new("haml_tag")
421: 
422:       name = name.to_s
423:       text = rest.shift.to_s unless [Symbol, Hash, NilClass].any? {|t| rest.first.is_a? t}
424:       flags = []
425:       flags << rest.shift while rest.first.is_a? Symbol
426:       attributes = Haml::Precompiler.build_attributes(haml_buffer.html?,
427:                                                       haml_buffer.options[:attr_wrapper],
428:                                                       rest.shift || {})
429: 
430:       if text.nil? && block.nil? && (haml_buffer.options[:autoclose].include?(name) || flags.include?(:/))
431:         haml_concat "<#{name}#{attributes} />"
432:         return ret
433:       end
434: 
435:       if flags.include?(:/)
436:         raise Error.new("Self-closing tags can't have content.") if text
437:         raise Error.new("Illegal nesting: nesting within a self-closing tag is illegal.") if block
438:       end
439: 
440:       tag = "<#{name}#{attributes}>"
441:       if block.nil?
442:         tag << text.to_s << "</#{name}>"
443:         haml_concat tag
444:         return ret
445:       end
446: 
447:       if text
448:         raise Error.new("Illegal nesting: content can't be both given to haml_tag :#{name} and nested within it.")
449:       end
450: 
451:       if flags.include?(:<)
452:         tag << capture_haml(&block).strip << "</#{name}>"
453:         haml_concat tag
454:         return ret
455:       end
456: 
457:       haml_concat tag
458:       tab_up
459:       block.call
460:       tab_down
461:       haml_concat "</#{name}>"
462: 
463:       ret
464:     end

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 [{to_s => String}] The attribute hash

[Source]

     # File lib/haml/helpers.rb, line 203
203:     def html_attrs(lang = 'en-US')
204:       {:xmlns => "http://www.w3.org/1999/xhtml", 'xml:lang' => lang, :lang => lang}
205:     end

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

[Source]

     # File lib/haml/helpers.rb, line 479
479:     def html_escape(text)
480:       text.to_s.gsub(/[\"><&]/n) {|s| HTML_ESCAPE[s]}
481:     end

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"

[Source]

    # File lib/haml/helpers.rb, line 80
80:     def init_haml_helpers
81:       @haml_buffer = Haml::Buffer.new(@haml_buffer, Haml::Engine.new('').send(:options_for_buffer))
82:       nil
83:     end

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

[Source]

     # File lib/haml/helpers.rb, line 501
501:     def is_haml?
502:       !@haml_buffer.nil? && @haml_buffer.active?
503:     end

Takes an `Enumerable` object and a block and iterates over the enum, yielding each element to a Haml block and putting the result into `<li>` 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`

[Source]

     # File lib/haml/helpers.rb, line 175
175:     def list_of(enum, &block)
176:       to_return = enum.collect do |i|
177:         result = capture_haml(i, &block)
178: 
179:         if result.count("\n") > 1
180:           result.gsub!("\n", "\n  ")
181:           result = "\n  #{result.strip}\n"
182:         else
183:           result.strip!
184:         end
185: 
186:         "<li>#{result}</li>"
187:       end
188:       to_return.join("\n")
189:     end

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

[Source]

     # File lib/haml/helpers.rb, line 94
 94:     def non_haml
 95:       was_active = @haml_buffer.active?
 96:       @haml_buffer.active = false
 97:       yield
 98:     ensure
 99:       @haml_buffer.active = was_active
100:     end

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

[Source]

     # File lib/haml/helpers.rb, line 280
280:     def precede(str, &block)
281:       "#{str}#{capture_haml(&block).chomp}\n"
282:     end

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

[Source]

     # File lib/haml/helpers.rb, line 134
134:     def preserve(input = nil, &block)
135:       return preserve(capture_haml(&block)) if block
136:       input.to_s.chomp("\n").gsub(/\n/, '&#x000A;').gsub(/\r/, '')
137:     end

@deprecated This will be removed in version 3.0. @see haml_concat

[Source]

     # File lib/haml/helpers.rb, line 344
344:     def puts(*args)
345:       warn "DEPRECATION WARNING:\nThe Haml #puts helper is deprecated and will be removed in version 3.0.\nUse the #haml_concat helper instead.\n"
346:       haml_concat(*args)
347:     end

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

[Source]

     # File lib/haml/helpers.rb, line 299
299:     def succeed(str, &block)
300:       "#{capture_haml(&block).chomp}#{str}\n"
301:     end

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

[Source]

     # File lib/haml/helpers.rb, line 261
261:     def surround(front, back = front, &block)
262:       output = capture_haml(&block)
263: 
264:       "#{front}#{output.chomp}#{back}\n"
265:     end

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 tab_up

[Source]

     # File lib/haml/helpers.rb, line 234
234:     def tab_down(i = 1)
235:       haml_buffer.tabulation -= i
236:     end

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 tab_down

[Source]

     # File lib/haml/helpers.rb, line 225
225:     def tab_up(i = 1)
226:       haml_buffer.tabulation += i
227:     end

[Validate]