AnyView
The AnyView gem provides helpers for common web related view rendering. The AnyView gem is a collection of mixins that work together to provide tags, forms asset paths and more. AnyView is based heavily on the Padrino framework helpers module.
The requirements of AnyView are kept very small. There’s two required methods inside your view context.
capture_content(*args, &block)
and
concat_content(string, opts ={})
By implementing these two methods on your view context, you’re able to get just about all the view helpers in anyview including form_for helpers.
Installation
$ sudo gem install any_view
This will install the required gems. Next, simply include the AnyView module into your view context
class ViewContext
include AnyView
end
If you’re using Tilt, then AnyView can provide the capture_content and concat_content helpers too. These will work for erubis, erb and haml templates.
class ViewContext
include AnyView::TiltBase
include AnyView
end
A full setup for a custom class, including rendering the tilt templates might look like this:
require 'dirge' # nice relative paths with ~
class Renderer
def self.path
@path ||= File.(~'./views')
end
def self.template(name)
@templates ||= {}
@templates[name] ||= Tilt.new(File.join(path, name))
@templates[name]
end
def template(name)
self.class.template(name)
end
def render(name, locals = {})
template(name).render(ViewContext.new, locals)
end
end
Usage would be as simple as
Renderer.new.render("my_template.erb")
Usage
Tag Helpers
Tag helpers are the basic building blocks used to construct html ‘tags’ within a view template. There are three major functions for this category: tag
, content_tag
and input_tag
.
The tag and content_tag are for building arbitrary html tags with a name and specified options. If the tag contains ‘content’ within then content_tag
is used. For example:
tag(:br, :style => ‘clear:both’) => <br style="clear:both" />
content_tag(:p, "demo", :class => ‘light’) => <p class="light">demo</p>
The input_tag is used to build tags that are related to accepting input from the user:
input_tag :text, :class => "demo" => <input type='text' class='demo' />
input_tag :password, :value => "secret", :class => "demo"
Note that all of these accept html options and result in returning a string containing html tags.
The list of defined helpers in the ‘tag helpers’ category:
-
tag(name, options={})
-
Creates an html tag with the given name and options
-
tag(:br, :style => 'clear:both')
=> <br style=“clear:both” /> -
tag(:p, :content => "demo", :class => 'large')
=> <p class=“large”>demo</p>
-
-
content_tag(name, content, options={})
-
Creates an html tag with given name, content and options
-
content_tag(:p, "demo", :class => 'light')
=> <p class=“light”>demo</p> -
content_tag(:p, :class => 'dark') { ...content... }
=> <p class=“dark”>…content…</p>
-
-
input_tag(type, options = {})
-
Creates an html input field with given type and options
-
input_tag :text, :class => "demo"
-
input_tag :password, :value => "secret", :class => "demo"
-
Asset Helpers
Asset helpers are intended to help insert useful html onto a view template such as stylesheet link tags , hyperlinks, mail_to links, images, stylesheets and javascript. An example of their uses would be on a simple view template:
# app/views/example.haml
...
%head
= stylesheet_link_tag 'layout'
= javascript_include_tag 'application'
%body
...
%p= link_to 'Blog', '/blog', :class => 'example'
%p Mail me at #{mail_to '[email protected]', "Fake Email Link", :cc => "[email protected]"}
%p= image_tag 'padrino.png', :width => '35', :class => 'logo'
The list of defined helpers in the ‘asset helpers’ category:
-
link_to(*args, &block)
-
Creates a link element with given name, url and options
-
link_to 'click me', '/dashboard', :class => 'linky'
-
link_to('/dashboard', :class => 'blocky') { ...content... }
-
-
mail_to(email, caption=nil, mail_options={})
-
Creates a mailto link tag to the specified email_address
-
mail_to "[email protected]"
-
mail_to "[email protected]", "My Email", :subject => "Feedback", :cc => '[email protected]'
-
-
image_tag(url, options={})
-
Creates an image element with given url and options
-
image_tag('icons/avatar.png')
-
-
stylesheet_link_tag(*sources)
-
Returns a stylesheet link tag for the sources specified as arguments
-
stylesheet_link_tag 'style', 'application', 'layout'
-
-
javascript_include_tag(*sources)
-
Returns an html script tag for each of the sources provided.
-
javascript_include_tag 'application', 'special'
-
To make use of these in a situation where you’re application is in a mounted url space, you should include a method uri_root
in your view_context. This allows you to put a uri prifix on the “/stylesheets/my_style.css” relative url
Form Helpers
Form helpers are the ‘standard’ form tag helpers you would come to expect when building forms. A simple example of constructing a non-object form would be:
- form_tag '/destroy', :class => 'destroy-form', :method => :delete do
- field_set_tag do
%p
= label_tag :username, :class => 'first'
= text_field_tag :username, :value => params[:username]
%p
= label_tag :password, :class => 'first'
= password_field_tag :password, :value => params[:password]
%p
= label_tag :strategy
= select_tag :strategy, :options => ['delete', 'destroy'], :selected => 'delete'
%p
= check_box_tag :confirm_delete
- field_set_tag(:class => 'buttons') do
= submit_tag "Remove"
The list of defined helpers in the ‘form helpers’ category:
-
form_tag(url, options={}, &block)
-
Constructs a form without object based on options
-
Supports form methods ‘put’ and ‘delete’ through hidden field
-
form_tag('/register', :class => 'example') { ... }
-
-
field_set_tag(*args, &block)
-
Constructs a field_set to group fields with given options
-
field_set_tag(:class => 'office-set') { }
-
field_set_tag("Office", :class => 'office-set') { }
-
-
error_messages_for(record, options={})
-
Constructs list html for the errors for a given object
-
error_messages_for @user
-
-
label_tag(name, options={}, &block)
-
Constructs a label tag from the given options
-
label_tag :username, :class => 'long-label'
-
label_tag(:username, :class => 'blocked-label') { ... }
-
-
hidden_field_tag(name, options={})
-
Constructs a hidden field input from the given options
-
hidden_field_tag :session_key, :value => 'secret'
-
-
text_field_tag(name, options={})
-
Constructs a text field input from the given options
-
text_field_tag :username, :class => 'long'
-
-
text_area_tag(name, options={})
-
Constructs a text area input from the given options
-
text_area_tag :username, :class => 'long'
-
-
password_field_tag(name, options={})
-
Constructs a password field input from the given options
-
password_field_tag :password, :class => 'long'
-
-
check_box_tag(name, options={})
-
Constructs a checkbox input from the given options
-
check_box_tag :remember_me, :checked => true
-
-
radio_button_tag(name, options={})
-
Constructs a radio button input from the given options
-
radio_button_tag :gender, :value => 'male'
-
-
select_tag(name, settings={})
-
Constructs a select tag with options from the given settings
-
select_tag(:favorite_color, :options => ['1', '2', '3'], :selected => '1')
-
select_tag(:more_color, :options => [['label', '1'], ['label2', '2']])
-
select_tag(:multiple_color, :options => [...], :multiple => true)
-
-
file_field_tag(name, options={})
-
Constructs a file field input from the given options
-
file_field_tag :photo, :class => 'long'
-
-
submit_tag(caption, options={})
-
Constructs a submit button from the given options
-
submit_tag "Create", :class => 'success'
-
-
button_tag(caption, options={})
-
Constructs an input (type => ‘button’) from the given options
-
button_tag "Cancel", :class => 'clear'
-
-
image_submit_tag(source, options={})
-
Constructs an image submit button from the given options
-
image_submit_tag "submit.png", :class => 'success'
-
FormBuilders
Form builders are full-featured objects allowing the construction of complex object-based forms using a simple, intuitive syntax.
A form_for using these basic fields might look like:
- form_for @user, '/register', :id => 'register' do |f|
= f.error_messages
%p
= f.label :username, :caption => "Nickname"
= f.text_field :username
%p
= f.label :email
= f.text_field :email
%p
= f.label :password
= f.password_field :password
%p
= f.label :is_admin, :caption => "Admin User?"
= f.check_box :is_admin
%p
= f.label :color, :caption => "Favorite Color?"
= f.select :color, :options => ['red', 'black']
%p
- fields_for @user.location do |location|
= location.text_field :street
= location.text_field :city
%p
= f.submit "Create", :class => 'button'
The list of defined helpers in the ‘form builders’ category:
-
form_for(object, url, settings={}, &block)
-
Constructs a form using given or default form_builder
-
Supports form methods ‘put’ and ‘delete’ through hidden field
-
Defaults to StandardFormBuilder but you can easily create your own!
-
form_for(@user, '/register', :id => 'register') { |f| ...field-elements... }
-
-
fields_for(object, settings={}, &block)
-
Constructs fields for a given object for use in an existing form
-
Defaults to StandardFormBuilder but you can easily create your own!
-
fields_for @user.assignment do |assignment| ... end
-
fields_for :assignment do |assigment| ... end
-
The following are fields provided by AbstractFormBuilder that can be used within a form_for or fields_for:
-
error_messages(options={})
-
Displays list html for the errors on form object
-
f.errors_messages
-
-
label(field, options={})
-
f.label :name, :class => 'long'
-
-
text_field(field, options={})
-
f.text_field :username, :class => 'long'
-
-
check_box(field, options={})
-
Uses hidden field to provide a ‘unchecked’ value for field
-
f.check_box :remember_me, :uncheck_value => 'false'
-
-
radio_button(field, options={})
-
f.radio_button :gender, :value => 'male'
-
-
hidden_field(field, options={})
-
f.hidden_field :session_id, :class => 'hidden'
-
-
text_area(field, options={})
-
f.text_area :summary, :class => 'long'
-
-
password_field(field, options={})
-
f.password_field :secret, :class => 'long'
-
-
file_field(field, options={})
-
f.file_field :photo, :class => 'long'
-
-
select(field, options={})
-
f.select(:state, :options => ['California', 'Texas', 'Wyoming'])
-
f.select(:state, :collection => @states, :fields => [:name, :id])
-
f.select(:state, :options => [...], :include_blank => true)
-
-
submit(caption, options={})
-
f.submit "Update", :class => 'long'
-
-
image_submit(source, options={})
-
f.image_submit "submit.png", :class => 'long'
-
There is also an additional StandardFormBuilder which builds on the abstract fields that can be used within a form_for.
A form_for using these standard fields might be:
- form_for @user, '/register', :id => 'register' do |f|
= f.error_messages
= f.text_field_block :name, :caption => "Full name"
= f.text_field_block :email
= f.check_box_block :remember_me
= f.select_block :fav_color, :options => ['red', 'blue']
= f.password_field_block :password
= f.submit_block "Create", :class => 'button'
and would generate this html (with each input contained in a paragraph and containing a label):
<form id="register" action="/register" method="post">
<p><label for="user_name">Full name: </label><input type="text" id="user_name" name="user[name]"></p>
...omitted...
<p><input type="submit" value="Create" class="button"></p>
</form>
The following are fields provided by StandardFormBuilder that can be used within a form_for or fields_for:
-
text_field_block(field, options={}, label_options={})
-
text_field_block(:nickname, :class => 'big', :caption => "Username")
-
-
text_area_block(field, options={}, label_options={})
-
text_area_block(:about, :class => 'big')
-
-
password_field_block(field, options={}, label_options={})
-
password_field_block(:code, :class => 'big')
-
-
file_field_block(field, options={}, label_options={})
-
file_field_block(:photo, :class => 'big')
-
-
check_box_block(field, options={}, label_options={})
-
check_box_block(:remember_me, :class => 'big')
-
-
select_block(field, options={}, label_options={})
-
select_block(:country, :option => ['USA', 'Canada'])
-
-
submit_block(caption, options={})
-
submit_block(:username, :class => 'big')
-
-
image_submit_block(source, options={})
-
image_submit_block('submit.png', :class => 'big')
-
You can also easily build your own FormBuilder which allows for customized fields and behavior:
class MyCustomFormBuilder < AbstractFormBuilder
# Here we have access to a number of useful variables
#
# * view_context (use this to invoke any helpers)(ex. view_context.hidden_field_tag(...))
# * object (the record for this form) (ex. object.valid?)
# * object_name (object's underscored type) (ex. object_name => 'admin_user')
#
# We also have access to self.field_types => [:text_field, :text_area, ...]
# In addition, we have access to all the existing field tag helpers (text_field, hidden_field, file_field, ...)
end
Once a custom builder is defined, any call to form_for can use the new builder:
- form_for @user, '/register', :builder => MyCustomFormBuilder, :id => 'register' do |f|
...fields here...
Format Helpers
Format helpers are several useful utilities for manipulating the format of text to achieve a goal. The format helper escape_html
is also aliased as h
and sanitize_html
The escape_html function is for taking an html string and escaping certain characters. escape_html
will escape ampersands, brackets and quotes to their HTML/XML entities. This is useful to sanitize user content before displaying this on a template.
escape_html('<hello>&<goodbye>') # => <hello>&<goodbye>
Format helpers also includes a number of useful text manipulation functions such as simple_format
, and truncate
.
simple_format("hello\nworld") # => "<p>hello<br/>world</p>"
truncate("Once upon a time in a world far far away", :length => 8) => "Once upon..."
The list of defined helpers in the ‘format helpers’ category:
-
simple_format(text, html_options)
-
Returns text transformed into HTML using simple formatting rules.
-
simple_format("hello\nworld")
=> “<p>hello<br/>world</p>”
-
-
truncate(text, *args)
-
Truncates a given text after a given :length if text is longer than :length (defaults to 30).
-
truncate("Once upon a time in a world far far away", :length => 8)
=> “Once upon…”
-
-
escape_html
(aliash
andh!
)-
(from RackUtils) Escape ampersands, brackets and quotes to their HTML/XML entities.
-
Copyright
Copyright © 2009 Daniel Neighman. See LICENSE for details.