Module: Haml::Helpers

Includes:
Helpers::ActionViewExtensions
Defined in:
/var/www/haml-pages/.haml/lib/haml/helpers.rb,
/var/www/haml-pages/.haml/lib/haml/helpers/xss_mods.rb,
/var/www/haml-pages/.haml/lib/haml/helpers/action_view_extensions.rb

Overview

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.

Defined Under Namespace

Modules: ActionViewExtensions, XssMods Classes: ErrorReturn

Constant Summary

@@action_view_defined =
defined?(ActionView)
@@force_no_action_view =
false

Class Method Summary

Instance Method Summary

Methods included from Helpers::ActionViewExtensions

#page_class, #with_raw_haml_concat

Class Method Details

+ (Boolean) action_view?

Whether or not ActionView is loaded

Returns:

  • (Boolean) — Whether or not ActionView is loaded


60
61
62
# File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 60

def self.action_view?
  @@action_view_defined
end

Instance Method Details

- (Boolean) block_is_haml?(block)

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

Parameters:

  • (Proc) block — A Ruby block

Returns:

  • (Boolean) — Whether or not block is defined directly in a Haml template


536
537
538
539
540
541
# File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 536

def block_is_haml?(block)
  eval('_hamlout', block.binding)
  true
rescue
  false
end

- capture_haml(*args, &block) {|args| ... }

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".

Parameters:

  • (Array) args — Arguments to pass into the block

Yields:

  • (args) — A block of Haml code that will be converted to a string

Yield Parameters:

  • (Array) argsargs


344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 344

def capture_haml(*args, &block)
  buffer = eval('_hamlout', block.binding) rescue haml_buffer
  with_haml_buffer(buffer) do
    position = haml_buffer.buffer.length

    haml_buffer.capture_position = position
    block.call(*args)

    captured = haml_buffer.buffer.slice!(position..-1).split(/^/)

    min_tabs = nil
    captured.each do |line|
      tabs = line.index(/[^ ]/) || line.length
      min_tabs ||= tabs
      min_tabs = min_tabs > tabs ? tabs : min_tabs
    end

    captured.map do |line|
      line[min_tabs..-1]
    end.join
  end
ensure
  haml_buffer.capture_position = nil
end

- (String) escape_once(text)

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

Parameters:

  • (String) text — The string to sanitize

Returns:

  • (String) — The sanitized string


515
516
517
518
519
# File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 515

def escape_once(text)
  Haml::Util.silence_warnings do
    text.to_s.gsub(/[\"><]|&(?!(?:[a-zA-Z]+|(#\d+));)/n) {|s| HTML_ESCAPE[s]}
  end
end

- find_and_preserve(input, tags = haml_buffer.options[:preserve]) - find_and_preserve(tags = haml_buffer.options[:preserve]) { ... }

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

Overloads:

  • - find_and_preserve(input, tags = haml_buffer.options[:preserve])

    Escapes newlines within a string.

    Parameters:

    • (String) input — The string within which to escape newlines
  • - find_and_preserve(tags = haml_buffer.options[:preserve]) { ... }

    Escapes newlines within a block of Haml code.

    Yields:

    • The block within which to escape newlines

Parameters:

  • (Array<String>) tags (defaults to: haml_buffer.options[:preserve]) — Tags that should have newlines escaped


115
116
117
118
119
120
# File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 115

def find_and_preserve(input = nil, tags = haml_buffer.options[:preserve], &block)
  return find_and_preserve(capture_haml(&block), input || tags) if block
  input.to_s.gsub(/<(#{tags.map(&Regexp.method(:escape)).join('|')})([^>]*)>(.*?)(<\/\1>)/im) do
    "<#{$1}#{$2}>#{preserve($3)}"
  end
end

- haml_concat(text = "")

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

Parameters:

  • (#to_s) text (defaults to: "") — The text to output


384
385
386
387
# File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 384

def haml_concat(text = "")
  haml_buffer.buffer << haml_indent << text.to_s << "\n"
  ErrorReturn.new("haml_concat")
end

- (String) haml_indent

The indentation string for the current line

Returns:

  • (String) — The indentation string for the current line


390
391
392
# File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 390

def haml_indent
  '  ' * haml_buffer.tabulation
end

- 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 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>

Overloads:

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

    Yields:

    • The block of Haml code within the tag
  • - haml_tag(name, text, *flags, attributes = {})

    Parameters:

    • (#to_s) text — The text within the tag

Parameters:

  • (#to_s) name — The name of the tag
  • (Array<Symbol>) flags — Haml end-of-tag flags


446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 446

def haml_tag(name, *rest, &block)
  ret = ErrorReturn.new("haml_tag")

  name = name.to_s
  text = rest.shift.to_s unless [Symbol, Hash, NilClass].any? {|t| rest.first.is_a? t}
  flags = []
  flags << rest.shift while rest.first.is_a? Symbol
  attributes = Haml::Precompiler.build_attributes(haml_buffer.html?,
                                                  haml_buffer.options[:attr_wrapper],
                                                  rest.shift || {})

  if text.nil? && block.nil? && (haml_buffer.options[:autoclose].include?(name) || flags.include?(:/))
    haml_concat "<#{name}#{attributes} />"
    return ret
  end

  if flags.include?(:/)
    raise Error.new("Self-closing tags can't have content.") if text
    raise Error.new("Illegal nesting: nesting within a self-closing tag is illegal.") if block
  end

  tag = "<#{name}#{attributes}>"
  if block.nil?
    tag << text.to_s << ""
    haml_concat tag
    return ret
  end

  if text
    raise Error.new("Illegal nesting: content can't be both given to haml_tag :#{name} and nested within it.")
  end

  if flags.include?(:<)
    tag << capture_haml(&block).strip << ""
    haml_concat tag
    return ret
  end

  haml_concat tag
  tab_up
  block.call
  tab_down
  haml_concat ""

  ret
end

- ({#to_s => String}) html_attrs(lang = 'en-US')

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'>

Parameters:

  • (String) lang (defaults to: 'en-US') — The value of xml:lang and lang

Returns:

  • ({#to_s => String}) — The attribute hash


203
204
205
# File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 203

def html_attrs(lang = 'en-US')
  {:xmlns => "http://www.w3.org/1999/xhtml", 'xml:lang' => lang, :lang => lang}
end

- (String) html_escape(text)

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”.

Parameters:

  • (String) text — The string to sanitize

Returns:

  • (String) — The sanitized string


506
507
508
# File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 506

def html_escape(text)
  text.to_s.gsub(/[\"><&]/n) {|s| HTML_ESCAPE[s]}
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 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"


80
81
82
83
# File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 80

def init_haml_helpers
  @haml_buffer = Haml::Buffer.new(@haml_buffer, Haml::Engine.new('').send(:options_for_buffer))
  nil
end

- (Boolean) 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.

Returns:

  • (Boolean) — Whether or not the current template is a Haml template


528
529
530
# File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 528

def is_haml?
  !@haml_buffer.nil? && @haml_buffer.active?
end

- list_of(enum, &block) {|item| ... }

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>

Parameters:

  • (Enumerable) enum — The list of objects to iterate over

Yields:

  • (item) — A block which contains Haml code that goes within list items

Yield Parameters:

  • item — An element of enum


175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 175

def list_of(enum, &block)
  to_return = enum.collect do |i|
    result = capture_haml(i, &block)

    if result.count("\n") > 1
      result.gsub!("\n", "\n  ")
      result = "\n  #{result.strip}\n"
    else
      result.strip!
    end

    "
  • #{result}
  • " end to_return.join("\n") 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.

    Yields:

    • A block which won’t register as Haml
    
    
    94
    95
    96
    97
    98
    99
    100
    # File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 94
    
    def non_haml
      was_active = @haml_buffer.active?
      @haml_buffer.active = false
      yield
    ensure
      @haml_buffer.active = was_active
    end

    - precede(str, &block) { ... }

    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>

    Parameters:

    • (String) str — The string to add before the Haml

    Yields:

    • A block of Haml to prepend to
    
    
    307
    308
    309
    # File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 307
    
    def precede(str, &block)
      "#{str}#{capture_haml(&block).chomp}\n"
    end

    - perserve(input) - perserve { ... } Also known as: flatten

    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.

    Overloads:

    • - perserve(input)

      Escapes newlines within a string.

      Parameters:

      • (String) input — The string within which to escape all newlines
    • - perserve { ... }

      Escapes newlines within a block of Haml code.

      Yields:

      • The block within which to escape newlines
    
    
    134
    135
    136
    137
    # File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 134
    
    def preserve(input = nil, &block)
      return preserve(capture_haml(&block)) if block
      input.to_s.chomp("\n").gsub(/\n/, '
    ').gsub(/\r/, '')
    end

    - puts(*args)

    Deprecated. This will be removed in version 3.0.

    See Also:

    
    
    371
    372
    373
    374
    # File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 371
    
    def puts(*args)
      warn "DEPRECATION WARNING:\nThe Haml #puts helper is deprecated and will be removed in version 3.0.\nUse the #haml_concat helper instead.\n"
      haml_concat(*args)
    end

    - succeed(str, &block) { ... }

    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>.

    Parameters:

    • (String) str — The string to add after the Haml

    Yields:

    • A block of Haml to append to
    
    
    326
    327
    328
    # File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 326
    
    def succeed(str, &block)
      "#{capture_haml(&block).chomp}#{str}\n"
    end

    - surround(front, back = front, &block) { ... }

    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>*

    Parameters:

    • (String) front — The string to add before the Haml
    • (String) back (defaults to: front) — The string to add after the Haml

    Yields:

    • A block of Haml to surround
    
    
    288
    289
    290
    291
    292
    # File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 288
    
    def surround(front, back = front, &block)
      output = capture_haml(&block)
    
      "#{front}#{output.chomp}#{back}\n"
    end

    - tab_down(i = 1)

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

    Parameters:

    • (Fixnum) i (defaults to: 1) — The number of tabs by which to decrease the indentation

    See Also:

    
    
    234
    235
    236
    # File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 234
    
    def tab_down(i = 1)
      haml_buffer.tabulation -= i
    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>

    Parameters:

    • (Fixnum) i (defaults to: 1) — The number of tabs by which to increase the indentation

    See Also:

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

    - with_tabs(i) { ... }

    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>

    Parameters:

    • (Fixnum) i — The number of tabs to use

    Yields:

    • A block in which the indentation will be i spaces
    
    
    257
    258
    259
    260
    261
    262
    263
    # File '/var/www/haml-pages/.haml/lib/haml/helpers.rb', line 257
    
    def with_tabs(i)
      old_tabs = haml_buffer.tabulation
      haml_buffer.tabulation = i
      yield
    ensure
      haml_buffer.tabulation = old_tabs
    end