Ruby on Rails/ActionView/Layout Files

Layout Files
The previous chapter explained how to render output to the default layout or to a special layout provided by you. You may have already looked inside such a layout file. Its default content will be similar to

Typically a layout's head section has an embedded tag for a stylesheet and the complete content is represented using a yield-tag

Asset tags
All asset tags, such as the "stylesheet_link_tag" are little helpers that generate the proper HTML for you. You can use this tags to embed CSS, Java Script and images or to provide RSS-feeds.

To embedded Javascript or CSS, you can use the according helpers: or if you want to include CSS

All these files are located in the public directory public/javascripts or public/stylesheets. There is no need to provide the extension as Rails will handle it automatically. To include multiple files just provide all the file names inside the tags:

Of course these files can be placed anywhere in your application, just be sure to provide the proper path:

To load all files inside your public/javascripts or public/styleheets use the appropriate tag with :all

When embedding CSS you can specify the media attribute inside the tag:

No modern web site is complete without using pictures and graphics so Rails provides you with its own image tag: As with JavaScript or CSS the Rails will look into public/images by default to find the proper picture. Note: that you do not need to tell Rails if you use .jpg, .gif or .png! You can also provide a custom path and HTML attributes

Yield
"yield" means that this is sort of a placeholder for the view that will be displayed inside your layout, but you are not limited to using a single yield:

To get access to the :header you can use the "<tt>content_for</tt>" method. So with the above example, that might be: Named yields can be used for menus, footers or sidebars to ease up maintenance. Just put them in your code and they will be placed in the right place.

Partials
It is time for a little more DRY. If you have a lot of HTML code that repeats itself in many different views (such as forms, dynamic menus,...) you might want to consider using partials: With partials, move the code that you use often into a separate file and place a link inside the files that should use your partials This will look inside the folder from where the partial gets called for a file named <tt>_form.html.erb</tt>. Use an underscore in your filename to tell Rails that it is a partial.

To move your partial to a separate folder use will look in "partials" for a file called <tt>_form.html.erb</tt>

Overall partials minimize the effort of copying the same code over and over, but to keep the needed code in single files that can be altered easily and used as often as desired.