動作文字 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::Blob
。
來源: 顯示 | 在 GitHub 上
# File actiontext/app/models/action_text/rich_text.rb, line 52 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 69 def to_plain_text body&.to_plain_text.to_s end
to_s 連結
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() 連結
傳回 body
屬性,使其可以在 Trix 編輯器中編輯。附加檔案的預覽會內嵌呈現在文中。
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 85 def to_trix_html body&.to_trix_html end