Rails视图常用帮助函数

1.cycle(first_value, *values)

# Alternate CSS classes for even and odd numbers...
 @items = [1,2,3,4]
 <table>
 <% @items.each do |item| %>
   <tr class="<%= cycle("odd", "even") -%>">
     <td>item</td>
   </tr>
 <% end %>
 </table>

2.image_tag生成image标签
<%= image_tag(product.image_url, class: 'list_image') %>
会生成下面的代码
<img alt="Leishen" class="list_image" src="/assets/leishen.jpg">

3.truncate截取字符

#`strip_tags`用于去html标签
truncate(strip_tags(product.description), length: 80)

truncate("Once upon a time in a world far far away")
# => "Once upon a time in a world..."

truncate("Once upon a time in a world far far away", length: 17)
# => "Once upon a ti..."

truncate("Once upon a time in a world far far away", length: 17, separator: ' ')
# => "Once upon a..."

truncate("And they found that many people were sleeping better.", length: 25, omission: '... (continued)')
# => "And they f... (continued)"

truncate("<p>Once upon a time in a world far far away</p>")
# => "<p>Once upon a time in a wo..."

truncate("Once upon a time in a world far far away") { link_to "Continue", "#" }
# => "Once upon a time in a wo...<a href="#">Continue</a>"

strip_tags(html)清除html标签

strip_tags("Strip <i>these</i> tags!")
# => Strip these tags!

strip_tags("<b>Bold</b> no more!  <a href='more.html'>See more here</a>...")
# => Bold no more!  See more here...

strip_tags("<div id='top-bar'>Welcome to my website!</div>")
# => Welcome to my website!

4.sprintf格式化字符串
sprintf("$%0.02f", 12)自动转换成$12.00

5.时间转换方法
product.updated_at.localtime.strftime('%Y/%m/%d %H:%S')

6.一般我们通过多对多关系获取到的数据都是一个集合对象,我们需要通过使用to_a方法将其转换成数组
line_items.to_a.sum {|item| item.total_price}

7.time_ago_in_words

time_ago_in_words(3.minutes.from_now)                 # => 3 minutes
time_ago_in_words(3.minutes.ago)                      # => 3 minutes
time_ago_in_words(Time.now - 15.hours)                # => about 15 hours
time_ago_in_words(Time.now)                           # => less than a minute
time_ago_in_words(Time.now, include_seconds: true) # => less than 5 seconds

from_time = Time.now - 3.days - 14.minutes - 25.seconds
time_ago_in_words(from_time)      # => 3 days

from_time = (3.days + 14.minutes + 25.seconds).ago
time_ago_in_words(from_time)      # => 3 days

8.渲染HTML元素sanitize

    原文作者:天赢金创
    原文地址: https://segmentfault.com/a/1190000000481721
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞