1

I have a Rails Action Text field :content and it renders fine if I accept the entire field but it's long and I just want to display a part of it.

<%= year.content %> works fine except it's too long.

<%= year.content.truncate(70) %> results in undefined method 'truncate' for #<ActionText::RichText:0x00007ffb811a6060>

<%= year.content.to_s.truncate(70) %> displays <div class="trix-content"> <div> <strong>Jack Marietich, restaura... which I could work with, but is there a method that I don't have to strip the beginning?

Greg
  • 2,359
  • 5
  • 22
  • 35

3 Answers3

8

Trix using rails actiontext add pure html which showed up after I posted but not before.

<%= year.content.to_plain_text.truncate(70) %>

https://api.rubyonrails.org/classes/ActionText/RichText.html#method-i-to_plain_text but even if I had found it, not sure I would have understood that this is what I needed.

Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88
Greg
  • 2,359
  • 5
  • 22
  • 35
1

If you are doing this for a preview, you can strip tags and then truncate. Something like this:

<%= truncate(strip_tags(year.content.to_s), length: 70) %>

Not that I'm advocating for monkey-patching, but this seems like it might be a good candidate for adding a custom method if this is something you plan on using often.

Colto
  • 612
  • 4
  • 14
0

If you would like to keep the styling, yet truncate the content (followed by a 'read more' or alike), check out the following css:

.line-clamp {
  display: -webkit-box;
  -webkit-line-clamp: 3; // number of lines
  -webkit-box-orient: vertical;  
  overflow: hidden;
}

<div class="line-clamp">
 <%= year.content %>
</div>

You can then use some basic JS toggle to remove the line-clamp class to reveal the rest of the content.