rails 字符串 转化为 html

本文介绍Rails中TextHelper模块的simple_format方法使用方法。该方法能够将文本转换为HTML格式,支持换行和段落标记,并能指定包裹标签及自定义类名。同时介绍了如何通过sanitize选项控制对HTML标签的过滤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

simple_format              http://apidock.com/rails/v4.0.2/ActionView/Helpers/TextHelper/simple_format
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html
my_text = "Here is some basic text...\n...with a line break."

simple_format(my_text)
# => "<p>Here is some basic text...\n<br />...with a line break.</p>"

simple_format(my_text, {}, wrapper_tag: "div")
# => "<div>Here is some basic text...\n<br />...with a line break.</div>"

more_text = "We want to put a paragraph...\n\n...right there."

simple_format(more_text)
# => "<p>We want to put a paragraph...</p>\n\n<p>...right there.</p>"

simple_format("Look ma! A class!", class: 'description')
# => "<p class='description'>Look ma! A class!</p>"

simple_format("<blink>Unblinkable.</blink>")
# => "<p>Unblinkable.</p>"

simple_format("<blink>Blinkable!</blink> It's true.", {}, sanitize: false)
# => "<p><blink>Blinkable!</span> It's true.</p>"

一个\n被认为是换行其之后是<br/>  两个\n被认为是分段其之前是</p>之后<p>

If you want to escape all content, you should invoke the h method before calling the text helper.
simple_format h('<a href="http://example.com/">Example</a>')
# => "<p>&lt;a href=\"http://example.com/\"&gt;Example&lt;/a&gt;</p>"

 

转载于:https://www.cnblogs.com/znsongshu/p/6080217.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值