Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an HTML safe truncate method in Rails?

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 the middle of an opening and closing tag, I'd like to close the open tag/s. For example;

html = "123<a href='#'>456</a>7890" truncate_markup(html, :length => 5) --> "123<a href='#'>45</a>" 
like image 841
Jesse Hattabaugh Avatar asked Dec 01 '10 00:12

Jesse Hattabaugh


People also ask

What does HTML safe do in Rails?

Considering Rails 3: html_safe actually "sets the string" as HTML Safe (it's a little more complicated than that, but it's basically it). This way, you can return HTML Safe strings from helpers or models at will. h can only be used from within a controller or view, since it's from a helper.

What is truncate in rails?

Method: String#truncateTruncates a given text after a given length if text is longer than length : "Once upon a time in a world far far away". truncate(27) # => "Once upon a time in a wo..." Pass a :separator to truncate text at a natural break: "Once upon a time in a world far far away".


2 Answers

the regular truncate function works fine, just pass :escape => false as an option to keep the HTML intact. eg:

truncate(@html_text, :length => 230, :omission => "" , :escape => false) 

RubyOnRails.org

*Edit I didn't read the question very carefully (or at all TBH), so this answer does not solve this question... It IS the answer I happened to be looking for though, so hopefully it helps 1 or 2 people :)

like image 149
msanteler Avatar answered Sep 27 '22 19:09

msanteler


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.
like image 37
gdelfino Avatar answered Sep 27 '22 19:09

gdelfino