Action Text RichText¶ ↑
RichText 记录在序列化的 body 属性中保存了 Trix 编辑器生成的内容。它还保存了对嵌入文件的所有引用,这些文件使用 Active Storage 进行存储。然后,该记录通过 has_rich_text 类方法与应用程序希望拥有富文本内容的 Active Record 模型相关联。
class Message < ActiveRecord::Base has_rich_text :content end message = Message.create!(content: "<h1>Funny times!</h1>") message.content #=> #<ActionText::RichText.... message.content.to_s # => "<h1>Funny times!</h1>" message.content.to_plain_text # => "Funny times!" message = Message.create!(content: "<div onclick='action()'>safe<script>unsafe</script></div>") message.content #=> #<ActionText::RichText.... message.content.to_s # => "<div>safeunsafe</div>" message.content.to_plain_text # => "safeunsafe"
方法
- E
- R
- T
实例公共方法
embeds 链接
从嵌入文件中返回 ActiveStorage::Attachment 记录。
附加的 ActiveStorage::Blob 记录在 before_validation 回调中从 body 中提取。
来源: 显示 | 在 GitHub 上
# File actiontext/app/models/action_text/rich_text.rb, line 55 has_many_attached :embeds
record 链接
返回关联的记录。
来源: 显示 | 在 GitHub 上
# File actiontext/app/models/action_text/rich_text.rb, line 46 belongs_to :record, polymorphic: true, touch: true
to_plain_text() 链接
返回 body 属性中包含的标记的纯文本版本,移除标签但编码 HTML 实体。
message = Message.create!(content: "<h1>Funny times!</h1>") message.content.to_plain_text # => "Funny times!"
注意:返回的字符串不是 HTML 安全的,不应在浏览器中渲染。
message = Message.create!(content: "<script>alert()</script>") message.content.to_plain_text # => "<script>alert()</script>"
来源: 显示 | 在 GitHub 上
# File actiontext/app/models/action_text/rich_text.rb, line 72 def to_plain_text body&.to_plain_text.to_s end
to_s 链接
将 RichText 安全地转换为 HTML String。
message = Message.create!(content: "<h1>Funny times!</h1>") message.content.to_s # => "<h1>Funny times!</h1>" message = Message.create!(content: "<div onclick='action()'>safe<script>unsafe</script></div>") message.content.to_s # => "<div>safeunsafe</div>"
来源: 显示 | 在 GitHub 上
# File actiontext/app/models/action_text/rich_text.rb, line 39 serialize :body, coder: ActionText::Content
to_trix_html() 链接
以 Trix 编辑器可编辑的格式返回 body 属性。附件的预览将内联渲染。
content = "<h1>Funny Times!</h1><figure data-trix-attachment='{\"sgid\":\"..."\}'></figure>"
message = Message.create!(content: content)
message.content.to_trix_html # =>
# <div class="trix-content">
# <h1>Funny times!</h1>
# <figure data-trix-attachment='{\"sgid\":\"..."\}'>
# <img src="http://example.org/rails/active_storage/.../funny.jpg">
# </figure>
# </div>
来源: 显示 | 在 GitHub 上
# File actiontext/app/models/action_text/rich_text.rb, line 88 def to_trix_html body&.to_trix_html end