在单词边界处将文本换行 [英] Wrapping text into lines at word boundaries

查看:38
本文介绍了在单词边界处将文本换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1) 我想用单词自动换行文本,以便每行不超过 56 个字符.有没有办法做到这一点,还是我需要自己动手?

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

我的观点:

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

将呈现:

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

2) 我想将文本缩进 4 个空格,以便:

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

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

将呈现:

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

推荐答案

我相信您正在寻找的功能是 word_wrap.这样的事情应该可以工作:

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

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

您可以将其与 gsub 结合使用以获得您想要的缩进:

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

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

但是您可能应该将其移动到辅助方法中以保持您的视图清洁.

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

这篇关于在单词边界处将文本换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆