---
title: "ruby on rails : 截取字符串，用 more代替"
author: "PBFox"
date: "2007-11-02T10:50:00Z"
tags: []
slug: "ruby-on-rails-more"
draft: false
lastmod: "2007-11-02T10:50:00Z"
id: 479261
url: "https://developerwork.iteye.com/blog/479261"
---

页面中的description比较长， 想截取一部分，后面的用more代替，点击more的时候显示全部。这种情况比较长见。代码如下：

在application.helper中写个方法：

def truncate\_with\_more (text, cutoff, id)  
if text.length &gt; cutoff  
result = text\[0, cutoff]  
result += "&lt;span id='text\_more\_link\_#{id}'&gt;&hellip;"  
result += "&lt;a href='#' onclick='$(\\"text\_more\_#{id}\\").show(); $(\\"text\_more\_link\_#{id}\\").hide(); return false;'&gt;"  
result += "more&lt;/a&gt;&lt;/span&gt;"  
result += "&lt;span id='text\_more\_#{id}' style='display: none;'&gt;"  
result += text\[cutoff, text.length]  
result += "&lt;/span&gt;"  
else  
result = text  
end

result  
end

页面中调用：  
&lt;%= truncate\_with\_more post.description, 200, "post\_#{post.id}" %&gt;