Module: Sinatra::HtmlHelpers

Defined in:
lib/sinatra/support/htmlhelpers.rb

Overview

Useful HTML helpers.

require 'sinatra/support/htmlhelpers'

class Main < Sinatra::Base
  helpers Sinatra::HtmlHelpers
end

Helpers

This provides the following helpers:

h - Escapes HTML output

<a href="<%= h url %>">

tag - Builds HTML tags

tag :a                     #=> "<a>"
tag :strong, "Yes"         #=> "<strong>Yes</strong>"
tag :a, "OK", href: "#"    #=> "<a href='#'>OK</a>"

Instance Method Summary collapse

Instance Method Details

#escape_attr(str) ⇒ Object



68
69
70
# File 'lib/sinatra/support/htmlhelpers.rb', line 68

def escape_attr(str)
  str.to_s.gsub("'", "&#39;").gsub('"', "&quot;")
end

#h(str) ⇒ Object

Returns an HTML sanitized string.



23
24
25
# File 'lib/sinatra/support/htmlhelpers.rb', line 23

def h(str)
  Rack::Utils.escape_html(str)
end

#select_options(pairs, current = nil, prompt = nil) ⇒ Object

Accepts a list of pairs and produces option tags.

Examples:


select_options([['One', 1], ['Two', 2]])
select_options([['One', 1], ['Two', 2]], 1)
select_options([['One', 1], ['Two', 2]], 1, '- Choose -')

# using it with the provided date helpers...
select_options year_choices, 2010 # select 2010 as default
select_options month_choices, 5 # select May as default
select_options day_choices, 25 # select the 25th as default

Parameters:

  • pairs (Array)

    a collection of label, value tuples.

  • current (Object) (defaults to: nil)

    the current value of this select.

  • prompt (#to_s) (defaults to: nil)

    a default prompt to place at the beginning of the list.



44
45
46
47
48
49
50
# File 'lib/sinatra/support/htmlhelpers.rb', line 44

def select_options(pairs, current = nil, prompt = nil)
  pairs.unshift([prompt, '']) if prompt

  pairs.map { |label, value|
    tag(:option, label, :value => value, :selected => (current == value))
  }.join("\n")
end

#self_closing?(tag) ⇒ Boolean

Returns:

  • (Boolean)


72
73
74
75
76
77
# File 'lib/sinatra/support/htmlhelpers.rb', line 72

def self_closing?(tag)
  @self_closing ||= [:area, :base, :basefont, :br, :hr,
                     :input, :img, :link, :meta]

  @self_closing.include?(tag.to_sym)
end

#tag(tag, content, atts = {}) ⇒ Object

Builds a tag.



53
54
55
56
57
58
59
# File 'lib/sinatra/support/htmlhelpers.rb', line 53

def tag(tag, content, atts = {})
  if self_closing?(tag)
    %(<#{ tag }#{ tag_attributes(atts) } />)
  else
    %(<#{ tag }#{ tag_attributes(atts) }>#{h content}</#{ tag }>)
  end
end

#tag_attributes(atts = {}) ⇒ Object



61
62
63
64
65
66
# File 'lib/sinatra/support/htmlhelpers.rb', line 61

def tag_attributes(atts = {})
  atts.inject([]) { |a, (k, v)| 
    a << (' %s="%s"' % [k, escape_attr(v)]) if v
    a
  }.join('')
end