跳至內文 跳至搜尋

Action View Raw Output 幫手

方法
R
S
T

實體公開方法

raw(stringish)

此方法在不跳脫字串的情況下進行輸出。由於標籤跳脫現在為預設值,因此當您不希望 Rails 自動跳脫標籤時可以使用此方法。如果資料來自於使用者的輸入,則不建議使用此方法。

例如

raw @user.name
# => 'Jimmy <alert>Tables</alert>'
# File actionview/lib/action_view/helpers/output_safety_helper.rb, line 18
def raw(stringish)
  stringish.to_s.html_safe
end

safe_join(array, sep = $,)

此方法會傳回一個與 Array#join 呼叫將會傳回的結果相似的 HTML 安全字串。陣列會被扁平化,而且所有項目,包括提供的分隔符號,都會經過 HTML 跳脫,除非它們是 HTML 安全的,而且傳回的字串會被標記為 HTML 安全。

safe_join([tag.p("foo"), "<p>bar</p>"], "<br>")
# => "<p>foo</p>&lt;br&gt;&lt;p&gt;bar&lt;/p&gt;"

safe_join([tag.p("foo"), tag.p("bar")], tag.br)
# => "<p>foo</p><br><p>bar</p>"
# File actionview/lib/action_view/helpers/output_safety_helper.rb, line 33
def safe_join(array, sep = $,)
  sep = ERB::Util.unwrapped_html_escape(sep)

  array.flatten.map! { |i| ERB::Util.unwrapped_html_escape(i) }.join(sep).html_safe
end

to_sentence(array, options = {})

將陣列轉換為以逗號分隔的句子,其中最後一個元素會與連結詞彙彙接。這是具有 html_safe 意識的 ActiveSupport 的 Array#to_sentence 版本。

# File actionview/lib/action_view/helpers/output_safety_helper.rb, line 43
def to_sentence(array, options = {})
  options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale)

  default_connectors = {
    words_connector: ", ",
    two_words_connector: " and ",
    last_word_connector: ", and "
  }
  if defined?(I18n)
    i18n_connectors = I18n.translate(:'support.array', locale: options[:locale], default: {})
    default_connectors.merge!(i18n_connectors)
  end
  options = default_connectors.merge!(options)

  case array.length
  when 0
    "".html_safe
  when 1
    ERB::Util.html_escape(array[0])
  when 2
    safe_join([array[0], array[1]], options[:two_words_connector])
  else
    safe_join([safe_join(array[0...-1], options[:words_connector]), options[:last_word_connector], array[-1]], nil)
  end
end