Truncating HTML formatted text field

Hi Alex, Regarding HTML Formatting text field (I have the following code), <%= h("#{@college_essay.content}").gsub(/\n/, '<br/>').html_safe %> I am wondering if I can co-apply truncation <%= truncate(@college_essay.content, :length => 720) %> The most obvious starting point for me was to come up with: <%= truncate(h("#{@college_essay.content}").gsub(/\n/, '<br/>').html_safe, length: 1250) %> This doesn't do html formatting though. Tried <%= truncate{h("#{@college_essay.content}").gsub(/\n/, '<br/>').html_safe, length: 1250} %> as well... Are you aware of a method that we can combine both tml formatting and truncating? Thanks!

Posted about 4 years ago by Harry Lee
Posted about 4 years ago by Alex Yang

Instead of using truncate(h(...)), have you tried h(truncate(...))? I would imagine that you would want to first truncate the text, then 'html_escape' any special characters. Here's an example:

Let's say you used '>' in your text. After 'html_escape', '>' will become '&gt;'. But if the truncation happens to cut this off, it could become '&g', in which case the original meaning will be lost. That's why I think it makes sense to truncate the text first before escaping. Hope that helps.

1
Posted about 4 years ago by Harry Lee

Oh shoot that was a bugger... yeap works perfectly!

1