简介:在erb中使用blocks,可以为 html,封装逻辑 module ApplicationHelper def admin_area(&block) content_tag(:div, :class => "admin", &block) if admin? end def admin? true end end
#234 simple_form
<%= simple_form_for @product do |f| %> <%= f.error_messages %> <%= f.input :name %> <%= f.input :price, :hint => "prices should be in USD" %> <%= f.input :released_on %> <%= f.association :category, :include_blank => false %> <%= f.input :rating, :collection => 1..5, :as => :radio %> <%= f.input :discontinued %> <%= f.button :submit %> <% end %>
#132 helpers-outside-views
1、在 model 在使用helper def description "This category has #{helpers.pluralize(products.count, 'product')}." end def helpers ActionController::Base.helpers end 2、在controller中使用helper flash[:notice] = "Successfully created #{@template.link_to('product', @product)}."
#7 layout
Layouts are view files that define the code that surrounds a template. They can be shared across many actions and controllers. 1、默认 全局 applicateion.html.erb controller相关 layout project.html.erb 2、动态指定 class ProjectsController < ApplicationController layout :user_layout protected def user_layout if current_user.admin? "admin" else "application" end end 。。。 end 3、直接指定 class ProjectsController < ApplicationController layout "admin" def index @projects = Project.find(:all) render :layout => 'projects' end render :layout => false end
#125 dynamic-layouts
简介:实现动态布局 application.rb def load_blog @current_blog = Blog.find_by_subdomain(current_subdomain) if @current_blog.nil? flash[:error] = "Blog invalid" redirect_to root_url else self.class.layout(@current_blog.layout_name || 'application') end end blogs_controller 1、使用application中的 load_blog before_filter :load_blog, :only => :show 2、简单地在controller中指定 layout :blog_layout def blog_layout "plain" @current_blog.layout_name end 3、用户自定义 erviroment.rb config.gem 'liquid' custom.html.erb <%= Liquid::Template.parse(@current_blog.custom_layout_content). render('page_content' => yield, 'page_title' => yield(:title))
# 8 Layouts and content_for
If you want to change something in the layout on a per-template basis, content_for is your answer! This allows templates to specify view code that can be placed anywhere in a layout. 通常,是template中的内容,通过yeild,填充到 layout中 也可以,tempate中的内容,能过content_for :title 转给 layout用,办法是 yield :title example template这个储存 <% content_for :head do %> <%= stylesheet_link_tag 'projects' %> <% end %> layouts中这个接收 yield :title
#30 Pretty Page Title
Using a Helper Method module ApplicationHelper def title(page_title) content_for(:title) { page_title } end end template <% title "Recent Episodes" %> layout<%= yield (:title) || "default page" %>