---
title: "Rails 中页面中常用函数 时间转换"
author: "vwangzhen"
date: "2008-09-18T18:42:58Z"
tags: []
categories: ["编程语言"]
slug: "rails"
draft: false
lastmod: "2009-03-03T14:38:58Z"
id: 243680
url: "https://rubyrails.iteye.com/blog/243680"
---

```
<%=sprintf("%0.2f" , 100)%>  
 输出：100.00  保留2位 
```

 

  page 渲染模板同时调用js方法

```
     render :update do |page|
      page.replace("price" , :partial => "price")
      #page.javascript_tag( 'price', "alert('aaa'');")
      page.call("javacriptmethod"); #javascriptmethod方法为你的js方法
     end  
```

 

 

函数：h  
描述：将html转义

```
# <%=h("<h1>中华人民共和国</h1>")%>  
# 输出： <h1>中华人民共和国</h1>  
```

 函数：truncate(text, length = 30, truncate\_string = "...")  
描述：截取指定长度的字符串，后面加省略号

```
 <%=truncate("中华人民共和国",6,"@@@")%>  
 输出：中华@@@
 后面有三个点，所以算五个了  
```

   
函数：strftime  
描述：把日期为指定格式

```
 <%=product.add_date.strftime("%Y-%m-%d") %>   输出: 2006-12-03  
其中product.add_date为数据库中的时间型字段  .
   
 <%=Time.now.strftime("%Y-%m-%d") %>  
 输出当前时间 2006-12-6  .
   
 <%=Time.now.strftime("%Y-%m-%d %H:%M:%S")>  
 页面输出：2006-12-6 9:7:13 .
时间转化为当地时间:


<%=Time.now.updated_at.getlocal .strftime("%Y-%m-%d %H:%M:%S")>  

```

 高亮highlight(text, phrases, highlighter = '&lt;strong class="highlight"&gt;\\1&lt;/strong&gt;')

```
方法一:  
highlight('You searched for: rails', 'rails', "<a href='search?q=\1'>\1</a>")

方法二 ：在页面渲染

page.visual_effect  :highlight, @task.dom_id, 
                    :startcolor => "'#ff0000'"
```

 

金钱格式化

 

&lt;% html\_title(l(:label\_project\_plural)) -%&gt;

 

```
    #  number_to_currency(1234567890.50, :unit => "&pound;", 

:separator => ",", :delimiter => "")
      #  # => &pound;1234567890,50
      #  number_to_currency(1234567890.50, :unit => "&pound;", 

:separator => ",", :delimiter => "", :format => "%n %u")
      #  # => 1234567890,50 &pound; 
```

 

标题seo 优化函数

```
  def html_title(*args)
    if args.empty?
      title = []
      title << @project.name if @project
      title += @html_title if @html_title
      title << Setting.app_title
      title.compact.join(' - ')
    else
      @html_title ||= []
      @html_title += args
    end
  end
```

 

样式交差循环显示:

```
  cycle('list-line-odd', 'list-line-even') 样式交差循环显示 
```