Rails每周闲碎(一): View

本文介绍了Rails框架中的几个关键视图技巧,包括ViewHelper的作用及使用、layout的概念与定制方法、flash在不同动作间传递临时信息的机制、FormHelper与FormBuilder的区别、text_field_tag与f.text_field的使用场景、collection_select的高级选项以及安全地显示用户输入的方法。

1. View Helper

 

    Helper中的方法用于给view提供一些帮助方法或者封装view中一些可以抽象或者需要组合的块。、

 

    根据rails的convention,相应的helper会自然的被view include。

 

    也可以在ApplicationController里面把所有helper都include进来:

 

 

helper :all

 

2. layout

 

    layout是Rails view的一个创新,比如application.html.erb的基本结构就是:

 

<div id="body">
        <%= yield %>
</div>

 

    具体可见:  Rails宝典之第八式: layout与content_for

 

    每个controller都可以定制自己的layout。

 

 

3. flash

 

    The flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create action that sets flash[:notice] = "Successfully created" before redirecting to a display action that can then expose the flash to its template. Actually, that exposure is automatically done.

 

 

class PostsController < ActionController::Base
    def create
      # save post
      flash[:notice] = "Successfully created post"
      redirect_to posts_path(@post)
    end

    def show
      # doesn't need to assign the flash notice to the template, that's done automatically
    end
  end

  show.html.erb
    <% if flash[:notice] %>
      <div class="notice"><%= flash[:notice] %></div>
    <% end %>

 

    本质上flash是存储在session中的一些信息,它在action之间传递,使用后立即清除。这为web应用中很多场景提供了便利,比如在注册成功 页面,我们需要显示注册成功的提示消息;比如在发帖成功页面,我们需要显示成功发帖提示信息。这些信息都是‘一次性’的,用过之后不需要再存在。

 

    同时,flash还提供了discard,keep,now,store等方法。详情请见:http://api.rubyonrails.org/classes/ActionController/Flash/FlashHash.html

 

 

4. FormHelper  FormBuilder

 

     FormHelper已经取代FormBuilder。代码里面的FormBuilder只是为了向后兼容。

 


5. text_field_tag 与 f.text_field
 
   它们分别存在于action_view helpers里的form_tag_helper.rb和form_helper.rb。

   form_helper里面的helper方法应该说更加适合用于生成一个与active_record对象相关的form,因为很多convention带来的方便。


   而用form_tag_helper生成的form自由度更高。

 

6. collection_select

 

    如果不需要强制默认值

 

    :include_blank - set to true or a prompt string if the first option element of the select element is a blank. Useful if there is not a default value required for the select element.

 

7.  h

 

    为了正确显示以及安全问题,不要忘了escape用户的输入数据。

 

<%=h @user.email %>

 

 

8. cycle  even odd

 

    rails的一个最重要的特点是丰富性,连这样的html helper方法也提供。

 

9. -

 

     模板源文件在“%>”标记后面都加上了换行符。模板经过渲染之后,<%  %>这句代码消失了,换行符却留了下来。

 

     一般而言,这不是什么大问题,因为HTML并不关心空白字符。不过,如果你用模板机制来创建电子邮件,或是生成的HTML中包含<pre >代码块,就需要去掉这些空行。为此,只要把rhtml代码的结尾标记由“%>”改为“-%>”即可,这里的减号就会告诉Rails将紧随其后的换行符全部去掉。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值