Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I control the number of lines displayed on a block of HTML-formatted user input?

Tags:

html

I have a Rails app that lets users input some HTML-formatted text (P, OL, UL, BLOCKQUOTE). I now want to display a short summary of this text, but want to ensure that I'm only showing <= 4 "lines". I can try to shorten the text by the number of words displayed, but that might still end up in lots of lines if there are one-word LI elements, etc. How can I do this?

like image 281
Newy Avatar asked Nov 27 '22 17:11

Newy


1 Answers

If I understand you correctly you want to show a sort of HTML preview of text that users type into a textarea, like the preview that shows below the textarea here on stackoverflow.

Probably the simplest way is with CSS.

#preview { height: 4em; overflow: hidden; }

That should work if the line-height is normal. That is of course just hiding the extra text. If hiding isn't acceptable and you must only generate 4 lines from Ruby to display then it is trickier. I don't know Ruby so I can't give you code examples. I would first off split the text at any point where a new line would be forced, like <br>, <p>, <li> etc. Then split those chunks further by figuring out how many characters can fit on one line and splitting the text at those intervals. Sorry I don't know the Ruby code but you should be able to split the text first on those line breaking characters and then split it further every X characters where X is the approximate amount of characters you can fit on a line. If you use a fixed width font you could figure out exactly how many characters fit on a line. So you would end up with an array or something and then you just glue the first 4 pieces together.

I hope that helps.

like image 103
Moss Avatar answered Dec 18 '22 20:12

Moss