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
- #escape_attr(str) ⇒ Object
-
#h(str) ⇒ Object
Returns an HTML sanitized string.
-
#select_options(pairs, current = nil, prompt = nil) ⇒ Object
Accepts a list of pairs and produces option tags.
- #self_closing?(tag) ⇒ Boolean
-
#tag(tag, content, atts = {}) ⇒ Object
Builds a tag.
- #tag_attributes(atts = {}) ⇒ Object
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("'", "'").gsub('"', """) 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.
44 45 46 47 48 49 50 |
# File 'lib/sinatra/support/htmlhelpers.rb', line 44 def (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
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 |