44

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>"

11 Answers 11

82

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 :)

3
  • 3
    Google brought me here and it was what i was looking for. Thanks.
    – penner
    Feb 23, 2014 at 1:12
  • 1
    You helped me. Quotes were showing by their code such as &ldquo; but by setting the escape option to false it works how I want. Thank you. Mar 13, 2014 at 0:11
  • 1
    Cool, but if there's an open tag on the truncated HTML, you will end up breaking your layout.
    – Abram
    Jun 10, 2019 at 15:18
36

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.
3
  • 3
    Are there any newer gems that have are still maintained and support Rails 4?
    – Alaric
    Dec 20, 2013 at 16:14
  • @RyanClark I would go with hgmnz/truncate_html. It's based on regular expressions and should work with any Rails version as long as the Ruby versions are compatible.
    – Daniel
    Apr 29, 2014 at 10:15
  • Unfortunately, hgmnz/truncate_html removes special characters. The code truncate_html('<p>aàáâäæãåāeèéêëēėęiîïíīįìoôöòóœøōõuûüùúū</p>', :length => 10) has an expected output of <p>aàáâäæãåāe</p> instead it returns <p>aeiou</p>.
    – dcangulo
    Dec 17, 2018 at 4:46
16

You should solve this problem with CSS rather than Ruby. You are doing something that affects the DOM layout, and there is no way to programmatically devise a solution that will work consistently.

Let's say you get your HTML parser gem working, and you find a lowest common denominator character count that will work most of the time.

What happens if you change font sizes, or your site layout? You'll have to recalculate the character count again.

Or let's say your html has something like this in it: <p><br /></p><br /> That is zero characters, however it would cause a big chunk of blank text to be inserted. It could even be a <blockquote> or <code> tag with too much padding or margin to throw your layout totally out of whack.

Or the inverse, let's say you have this 3&nbsp;&#8773;&nbsp;&#955; (3 ≅ λ) That is 26 characters long, but for display purposes it is only 5.

The point being that character count tells you nothing about how something will render in the browser. Not to mention the fact HTML parsers are hefty pieces of code that can at times be unreliable.

Here is some good CSS to deal with this. The :after pseudo class will add a white fade to the last line of content. Very nice transition.

body { font-size: 16px;}
p {font-size: 1em; line-height: 1.2em}
/* Maximum height math is:
   line-height * #oflines - 0.4
   the 0.4 offset is to make the cutoff  look nicer */
.lines-3{height: 3.2em;}
.lines-6{height: 6.8em;}
.truncate {overflow: hidden; position:relative}
.truncate:after{
    content:""; 
    height: 1em; 
    display: block; 
    width: 100%; 
    position:absolute;
    background-color:white; 
    opacity: 0.8; 
    bottom: -0.3em
}

You can add as many .lines-x classes as you see fit. I used em but px is just as good.

Then apply this to your element: <div class="truncate lines-3">....lots of stuff.. </div>

and the fiddle: http://jsfiddle.net/ke87h/

3
  • This is how I approached the problem in the site I work for. When JavaScript is available, I truncate characters off the end until it fits with an ellipses at the end. Doing the truncate server-side by a number of characters can lead to jagged results when a line has a lot of thin or wide characters. Jun 10, 2013 at 18:21
  • This is great. You can sanitize / strip html tags on the server side if you need to strip specific elements as well. Apr 11, 2014 at 15:53
  • So much cleaner! Good job
    – Vlad
    Nov 28, 2017 at 10:18
6

You could use the truncate_html plugin for this. It uses nokogiri and htmlentities gems and does exactly what the plugin name suggests.

4

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.

1
  • Using this one.
    – Abram
    Jun 10, 2019 at 15:20
4

This will help you without any extra effort

raw your_string.truncate(200)
2
  • "..not including the HTML markup", this code work with HTML Nov 24, 2015 at 14:51
  • 3
    nice, i used like this sanitize(sanitize("my text <em>with html</em>", tags: ['h1']).truncate(150)) the first sanitize will complete the missing markup, the inner sanitize will remove my unwanted tags and truncate on the end will truncate like an html_safe, thanks
    – Alexis
    Dec 7, 2015 at 7:20
2
your_tagged_string.truncate(60).html_safe
1

You can use

truncate(html.gsub(/(<[^>]+>)/, ''), 5)
3
  • 1
    This would strip out all the html, wouldn't it?
    – Arcolye
    Jul 11, 2013 at 11:59
  • Add 'separator' param to prevent word crop: truncate(html.gsub(/(<[^>]+>)/, ''), length: 5, separator: ' ') Sep 4, 2013 at 16:20
  • 2
    Might as well use Rails' strip_tags helper to do this.
    – alexpls
    Jan 8, 2014 at 8:37
1

You can use the truncate method in combination with sanitize.

truncate(sanitize(html_content), length: 100, separator: '</p>', escape: false)

This will truncate your HTML using the separator but it can produce HTML without closing tags. To fix this we can use the sanitize method again, which will clean the HTML and add the missing tags.

sanitize(truncate(sanitize(html_content), length: 100, separator: '</p>', escape: false))
0

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"

-2

Solving this problem from the client side:

view:

<script>
  $(function() {
    $('.post-preview').each(function() {
      var tmp_height = $(this).innerHeight();
      if ((tmp_height > 100) && (tmp_height < 200)) {
        $(this).addClass("preview-small");
      }
      else if (tmp_height >= 200) {
        $(this).addClass("preview-large")
      }
      else {
        //do nothing
      }
    });
  });
</script>

css

.preview-small {
  height: 100px;
  overflow: hidden;
}

.preview-large {
  height: 200px;
  overflow: hidden;
}
1
  • 1
    This question is for Rails, check title: "Is there an HTML safe truncate method in Rails?" Nov 24, 2015 at 14:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.