Module Haml::Helpers

  1. lib/haml/helpers.rb
  2. 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.

Included modules

  1. ActionViewExtensions

Public class methods

action_view? ()

Returns whether or not ActionView is installed on the system.

[show source]
    # File lib/haml/helpers.rb, line 16
16:     def self.action_view?
17:       @@action_view_defined
18:     end

Public instance methods

capture_haml (*args, &block)

Captures the result of the given 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".

[show source]
     # File lib/haml/helpers.rb, line 256
256:     def capture_haml(*args, &block)
257:       capture_haml_with_buffer(haml_buffer.buffer, *args, &block)
258:     end
escape_once (text)

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

[show source]
     # File lib/haml/helpers.rb, line 367
367:     def escape_once(text)
368:       text.to_s.gsub(/[\"><]|&(?!([a-zA-Z]+|(#\d+));)/) { |s| HTML_ESCAPE[s] }
369:     end
find_and_preserve(input, tags = haml_buffer.options[:preserve])
find_and_preserve {...}

Uses preserve to convert any newlines inside whitespace-sensitive tags into the HTML entities for endlines. @tags@ is an array of tags to preserve. It defaults to the value of the :preserve option.

[show source]
    # File lib/haml/helpers.rb, line 70
70:     def find_and_preserve(input = '', tags = haml_buffer.options[:preserve], &block)
71:       return find_and_preserve(capture_haml(&block)) if block
72: 
73:       input = input.to_s
74:       input.gsub(/<(#{tags.map(&Regexp.method(:escape)).join('|')})([^>]*)>(.*?)(<\/\1>)/im) do
75:         "<#{$1}#{$2}>#{preserve($3)}</#{$1}>"
76:       end
77:     end
flatten (input = '', &block)

Alias for preserve

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

Creates an HTML tag with the given name and optionally text and attributes. Can take a block that will be executed between when the opening and closing tags are output. If the block is a Haml block or outputs text using puts, 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.

For example,

  haml_tag :table do
    haml_tag :tr do
      haml_tag :td, {:class => 'cell'} do
        haml_tag :strong, "strong!"
        puts "data"
      end
      haml_tag :td do
        puts "more_data"
      end
    end
  end

outputs

  <table>
    <tr>
      <td class='cell'>
        <strong>
          strong!
        </strong>
        data
      </td>
      <td>
        more_data
      </td>
    </tr>
  </table>
[show source]
     # File lib/haml/helpers.rb, line 312
312:     def haml_tag(name, *rest, &block)
313:       name = name.to_s
314:       text = rest.shift if rest.first.is_a? String
315:       flags = []
316:       flags << rest.shift while rest.first.is_a? Symbol
317:       attributes = Haml::Precompiler.build_attributes(haml_buffer.html?,
318:                                                       haml_buffer.options[:attr_wrapper],
319:                                                       rest.shift || {})
320: 
321:       if text.nil? && block.nil? && (haml_buffer.options[:autoclose].include?(name) || flags.include?(:/))
322:         puts "<#{name}#{attributes} />"
323:         return nil
324:       end
325: 
326:       if flags.include?(:/)
327:         raise Error.new("Self-closing tags can't have content.") if text
328:         raise Error.new("Illegal nesting: nesting within a self-closing tag is illegal.") if block
329:       end
330: 
331:       tag = "<#{name}#{attributes}>"
332:       if block.nil?
333:         tag << text.to_s << "</#{name}>"
334:         puts tag
335:         return
336:       end
337: 
338:       if text
339:         raise Error.new("Illegal nesting: content can't be both given to haml_tag :#{name} and nested within it.")
340:       end
341: 
342:       if flags.include?(:<)
343:         tag << capture_haml(&block).strip << "</#{name}>"
344:         puts tag
345:         return
346:       end
347: 
348:       puts tag
349:       tab_up
350:       block.call
351:       tab_down
352:       puts "</#{name}>"
353:       nil
354:     end
html_attrs (lang = 'en-US')

Returns a hash containing default assignments for the xmlns and xml:lang attributes of the html HTML element. It also takes an optional argument for the value of xml:lang and lang, which defaults to ‘en-US’. For example,

  %html{html_attrs}

becomes

  <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en-US' lang='en-US'>
[show source]
     # File lib/haml/helpers.rb, line 154
154:     def html_attrs(lang = 'en-US')
155:       {:xmlns => "http://www.w3.org/1999/xhtml", 'xml:lang' => lang, :lang => lang}
156:     end
html_escape (text)

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

[show source]
     # File lib/haml/helpers.rb, line 361
361:     def html_escape(text)
362:       text.to_s.gsub(/[\"><&]/) { |s| HTML_ESCAPE[s] }
363:     end
init_haml_helpers ()

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 rendering 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"
[show source]
    # File lib/haml/helpers.rb, line 39
39:     def init_haml_helpers
40:       @haml_buffer = Haml::Buffer.new(@haml_buffer, Haml::Engine.new('').send(:options_for_buffer))
41:       nil
42:     end
is_haml? ()

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.

[show source]
     # File lib/haml/helpers.rb, line 376
376:     def is_haml?
377:       !@haml_buffer.nil? && @haml_buffer.active?
378:     end
list_of (array) {|item| ...}

Takes an Enumerable object and a block and iterates over the object, 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>
[show source]
     # File lib/haml/helpers.rb, line 126
126:     def list_of(array, &block) # :yields: item
127:       to_return = array.collect do |i|
128:         result = capture_haml(i, &block)
129: 
130:         if result.count("\n") > 1
131:           result.gsub!("\n", "\n  ")
132:           result = "\n  #{result.strip}\n"
133:         else
134:           result.strip!
135:         end
136: 
137:         "<li>#{result}</li>"
138:       end
139:       to_return.join("\n")
140:     end
non_haml { ... }

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.

[show source]
    # File lib/haml/helpers.rb, line 54
54:     def non_haml
55:       was_active = @haml_buffer.active?
56:       @haml_buffer.active = false
57:       res = yield
58:       @haml_buffer.active = was_active
59:       res
60:     end
precede (char, &block)

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

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

Produces:

  *<span class='small'>Not really</span>
[show source]
     # File lib/haml/helpers.rb, line 224
224:     def precede(char, &block)
225:       "#{char}#{capture_haml(&block).chomp}\n"
226:     end
preserve(input)
preserve {...}

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

[show source]
    # File lib/haml/helpers.rb, line 86
86:     def preserve(input = '', &block)
87:       return preserve(capture_haml(&block)) if block
88: 
89:       input.chomp("\n").gsub(/\n/, '&#x000A;').gsub(/\r/, '')
90:     end
puts (text = "")

Outputs text directly to the Haml buffer, with the proper tabulation

[show source]
     # File lib/haml/helpers.rb, line 261
261:     def puts(text = "")
262:       haml_buffer.buffer << ('  ' * haml_buffer.tabulation) << text.to_s << "\n"
263:       nil
264:     end
succeed (char, &block)

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

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

Produces:

  click
  <a href='thing'>here</a>.
[show source]
     # File lib/haml/helpers.rb, line 241
241:     def succeed(char, &block)
242:       "#{capture_haml(&block).chomp}#{char}\n"
243:     end
surround (front, back = nil, &block)

Surrounds the given block of Haml code with the given characters, 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>*
[show source]
     # File lib/haml/helpers.rb, line 206
206:     def surround(front, back = nil, &block)
207:       back ||= front
208:       output = capture_haml(&block)
209: 
210:       "#{front}#{output.chomp}#{back}\n"
211:     end
tab_down (i = 1)

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

See also tab_up.

[show source]
     # File lib/haml/helpers.rb, line 182
182:     def tab_down(i = 1)
183:       haml_buffer.tabulation -= i
184:     end
tab_up (i = 1)

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>
[show source]
     # File lib/haml/helpers.rb, line 174
174:     def tab_up(i = 1)
175:       haml_buffer.tabulation += i
176:     end