Jump to content

Ruby on Rails/Examples/HTML4.01

From Wikibooks, open books for an open world

Rails generates XHTML by default. It can be made to generate HTML4.01 that can be validated with The W3C HTML validator.

DOCTYPE

[edit | edit source]

Layouts begin with the HTML4.01 Strict DOCTYPE:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 

ApplicationHelper

[edit | edit source]

application_helper.rb looks something like this:

module Html4ize  # Supports making alternative versions of Rails helpers that output HTML  # 4.01 markup as opposed to XHTML. Example:  #  # html4_version_of :submit_tag  #  # ..which creates a submit_tag_html4 helper that takes the same options as  # submit_tag but which renders HTML 4.01.  #  def html4_version_of helper_name  define_method "#{helper_name}_html4" do |*args|  html = send helper_name, *args  html.gsub! " />", ">"  html  end  end  def html4_versions_of *helper_names  helper_names.each do |helper_name|  html4_version_of helper_name  end  end  class << self  def included receiver  receiver.extend Html4ize  end  end end # Methods added to this helper will be available to all templates in the application. module ApplicationHelper  include Html4ize  html4_versions_of :stylesheet_link_tag, :image_tag, :text_field, :submit_tag  ... end # Extend FormBuilder with our own helper methods class ActionView::Helpers::FormBuilder  include Html4ize  html4_versions_of :text_field, :check_box, :hidden_field, :submit  ... end 

Views

[edit | edit source]

Views can then refer to the newly-wrapped helpers:

 ...  <%= image_tag_html4 "logo.png" %>  ...  <% form_for :person do |form| %>  <div><b>Name:</b><%= form.text_field_html4 :name %></div>  ...  <div class="submit"><%= form.submit_html4 "Save" %></div>  <% end %>