Is there an HTML safe truncate method in Rails?

后端 未结 10 664
执笔经年
执笔经年 2020-12-24 05:45

I have a string of HTML in Rails. I\'d like to truncate the string after a certain number of characters not including the HTML markup. Also, if the split happens to fall in

相关标签:
10条回答
  • 2020-12-24 06:03

    There are two completely different solutions both with the same name: truncate_html

    1. https://github.com/ianwhite/truncate_html : This is a gem and uses an html parser (nokogiri)
    2. https://github.com/hgmnz/truncate_html : This is a file you put in your helpers directory. It uses regular expressions and has no dependencies.
    0 讨论(0)
  • 2020-12-24 06:06

    We can do that with the help of simple_format http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format

    html = "123<a href='#'>456</a>7890"
    simle_format(truncate_markup(html, :length => 5)) 
    

    => "123 456 7890"

    0 讨论(0)
  • 2020-12-24 06:11

    We had this need in zendone.com. The problem was that the existing solutions were very slow when truncating long HTML documents (MBs) into shorter ones (KBs). I ended up coding a library based in Nokogiri called truncato. The library includes some benchmarks comparing its performance with other libs.

    0 讨论(0)
  • 2020-12-24 06:13
    your_tagged_string.truncate(60).html_safe
    
    0 讨论(0)
提交回复
热议问题