| Module | Haml::Helpers |
| In: |
lib/haml/helpers.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.
| HTML_ESCAPE | = | { '&'=>'&', '<'=>'<', '>'=>'>', '"'=>'"', "'"=>''', } | Characters that need to be escaped to HTML entities from user input |
@return [Boolean] Whether or not ActionView is loaded
# File lib/haml/helpers.rb, line 60
60: def self.action_view?
61: @@action_view_defined
62: end
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 505
505: def block_is_haml?(block)
506: eval('_hamlout', block.binding)
507: true
508: rescue
509: false
510: 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`
# File lib/haml/helpers.rb, line 320
320: def capture_haml(*args, &block)
321: buffer = eval('_hamlout', block.binding) rescue haml_buffer
322: with_haml_buffer(buffer) do
323: position = haml_buffer.buffer.length
324:
325: haml_buffer.capture_position = position
326: block.call(*args)
327:
328: captured = haml_buffer.buffer.slice!(position..-1).split(/^/)
329:
330: min_tabs = nil
331: captured.each do |line|
332: tabs = line.index(/[^ ]/) || line.length
333: min_tabs ||= tabs
334: min_tabs = min_tabs > tabs ? tabs : min_tabs
335: end
336:
337: captured.map do |line|
338: line[min_tabs..-1]
339: end.join
340: end
341: ensure
342: haml_buffer.capture_position = nil
343: 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
# File lib/haml/helpers.rb, line 486
486: def escape_once(text)
487: text.to_s.gsub(/[\"><]|&(?!([a-zA-Z]+|(#\d+));)/) { |s| HTML_ESCAPE[s] }
488: 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
# 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:
118: input = input.to_s
119: input.gsub(/<(#{tags.map(&Regexp.method(:escape)).join('|')})([^>]*)>(.*?)(<\/\1>)/im) do
120: "<#{$1}#{$2}>#{preserve($3)}</#{$1}>"
121: end
122: end
@return [String] The indentation string for the current line
# File lib/haml/helpers.rb, line 366
366: def haml_indent
367: ' ' * haml_buffer.tabulation
368: 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
# File lib/haml/helpers.rb, line 422
422: def haml_tag(name, *rest, &block)
423: ret = ErrorReturn.new("haml_tag")
424:
425: name = name.to_s
426: text = rest.shift.to_s unless [Symbol, Hash, NilClass].any? {|t| rest.first.is_a? t}
427: flags = []
428: flags << rest.shift while rest.first.is_a? Symbol
429: attributes = Haml::Precompiler.build_attributes(haml_buffer.html?,
430: haml_buffer.options[:attr_wrapper],
431: rest.shift || {})
432:
433: if text.nil? && block.nil? && (haml_buffer.options[:autoclose].include?(name) || flags.include?(:/))
434: haml_concat "<#{name}#{attributes} />"
435: return ret
436: end
437:
438: if flags.include?(:/)
439: raise Error.new("Self-closing tags can't have content.") if text
440: raise Error.new("Illegal nesting: nesting within a self-closing tag is illegal.") if block
441: end
442:
443: tag = "<#{name}#{attributes}>"
444: if block.nil?
445: tag << text.to_s << "</#{name}>"
446: haml_concat tag
447: return ret
448: end
449:
450: if text
451: raise Error.new("Illegal nesting: content can't be both given to haml_tag :#{name} and nested within it.")
452: end
453:
454: if flags.include?(:<)
455: tag << capture_haml(&block).strip << "</#{name}>"
456: haml_concat tag
457: return ret
458: end
459:
460: haml_concat tag
461: tab_up
462: block.call
463: tab_down
464: haml_concat "</#{name}>"
465:
466: ret
467: 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 [Hash<to_s, String>] The attribute hash
# File lib/haml/helpers.rb, line 206
206: def html_attrs(lang = 'en-US')
207: {:xmlns => "http://www.w3.org/1999/xhtml", 'xml:lang' => lang, :lang => lang}
208: end
Returns a copy of `text` with ampersands, angle brackets and quotes escaped into HTML entities.
@param text [String] The string to sanitize @return [String] The sanitized string
# File lib/haml/helpers.rb, line 477
477: def html_escape(text)
478: text.to_s.gsub(/[\"><&]/) { |s| HTML_ESCAPE[s] }
479: 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"
# 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
# File lib/haml/helpers.rb, line 497
497: def is_haml?
498: !@haml_buffer.nil? && @haml_buffer.active?
499: 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`
# File lib/haml/helpers.rb, line 178
178: def list_of(enum, &block)
179: to_return = enum.collect do |i|
180: result = capture_haml(i, &block)
181:
182: if result.count("\n") > 1
183: result.gsub!("\n", "\n ")
184: result = "\n #{result.strip}\n"
185: else
186: result.strip!
187: end
188:
189: "<li>#{result}</li>"
190: end
191: to_return.join("\n")
192: 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
# 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
# File lib/haml/helpers.rb, line 283
283: def precede(str, &block)
284: "#{str}#{capture_haml(&block).chomp}\n"
285: 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
# File lib/haml/helpers.rb, line 136
136: def preserve(input = '', &block)
137: return preserve(capture_haml(&block)) if block
138:
139: input.chomp("\n").gsub(/\n/, '
').gsub(/\r/, '')
140: end
@deprecated This will be removed in version 2.4. @see \{haml_concat}
# File lib/haml/helpers.rb, line 347
347: def puts(*args)
348: warn "DEPRECATION WARNING:\nThe Haml #puts helper is deprecated and will be removed in version 2.4.\nUse the #haml_concat helper instead.\n"
349: haml_concat(*args)
350: 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
# File lib/haml/helpers.rb, line 302
302: def succeed(str, &block)
303: "#{capture_haml(&block).chomp}#{str}\n"
304: 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
# File lib/haml/helpers.rb, line 264
264: def surround(front, back = front, &block)
265: output = capture_haml(&block)
266:
267: "#{front}#{output.chomp}#{back}\n"
268: 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
# File lib/haml/helpers.rb, line 228
228: def tab_up(i = 1)
229: haml_buffer.tabulation += i
230: end