Created
August 3, 2010 01:12
-
-
Save huacnlee/505643 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Ruby on Rails truncate_html HTML截断并保持HTML标签不出错 | |
# HTML截断并保持HTML标签不出错 | |
# 可以放入 application_helper.rb 里面 | |
# 前台调用 truncate_html(html_text,:length => 1000) | |
def truncate_html(html, options={}) | |
# Does not behave identical to current Rails truncate method i.e. you must pass options as a hash not just values | |
# Sample usage: <%= html_truncate(category.description, :length => 120, :omission => "(continued...)" ) -%>... | |
previous_tag = "" | |
text, result = [], [] | |
# get all text (including punctuation) and tags and stick them in a hash | |
html.scan(/<\/?[^>]*>|[A-Za-z.,;!"'?]+/).each { |t| text << t } | |
text.each do |str| | |
if options[:length] > 0 | |
if str =~ /<\/?[^>]*>/ | |
previous_tag = str | |
result << str | |
else | |
result << str | |
options[:length] -= str.length | |
end | |
else | |
# now stick the next tag with a </> that matches the previous open tag on the end of the result | |
if str =~ /<\/([#{previous_tag}]*)>/ | |
result << str | |
else | |
end | |
end | |
end | |
return result.join(" ") + options[:omission].to_s | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment