Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
983 views
in Technique[技术] by (71.8m points)

ruby on rails - Wrapping text into lines at word boundaries

1) I want to auto wrap a text by words so that each line does not exceed 56 characters. Is there a method for doing this, or do I need to roll my own?

@comment_text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."

My view:

<%= @comment_text.cool_string_function( 56 ) %>

would render:

Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et 
dolore magna aliqua.

2) I want to indent the text by 4 spaces so that:

<%= @comment_text.cool_string_function( {:width => 56, :indent => 4} ) %>

would render:

    Lorem ipsum dolor sit amet, consectetur adipisicing
    elit, sed do eiusmod tempor incididunt ut labore et 
    dolore magna aliqua.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I believe the function you are looking for is word_wrap. Something like this should work:

<%= word_wrap @comment_text, :line_width => 56 %>

You can combine that with gsub to get the indentation you desire:

<%= word_wrap(@comment_text, :line_width => 52).gsub("
", "
    ") %>

But you should probably move that into a helper method to keep your view clean.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...