instance method
highlight
Ruby on Rails 4.2.9
Since v2.2.3Signature
highlight(text, phrases, options = {})
Highlights one or more phrases everywhere in text by inserting it into a :highlighter string. The highlighter can be specialized by passing :highlighter as a single-quoted string with \1 where the phrase is to be inserted (defaults to ‘<mark>\1</mark>’) or passing a block that receives each matched term.
highlight('You searched for: rails', 'rails')
# => You searched for: <mark>rails</mark>
highlight('You searched for: rails', /for|rails/)
# => You searched <mark>for</mark>: <mark>rails</mark>
highlight('You searched for: ruby, rails, dhh', 'actionpack')
# => You searched for: ruby, rails, dhh
highlight('You searched for: rails', ['for', 'rails'], highlighter: '<em>\1</em>')
# => You searched <em>for</em>: <em>rails</em>
highlight('You searched for: rails', 'rails', highlighter: '<a href="search?q=\1">\1</a>')
# => You searched for: <a href="search?q=rails">rails</a>
highlight('You searched for: rails', 'rails') { |match| link_to(search_path(q: match, match)) }
# => You searched for: <a href="search?q=rails">rails</a>
Parameters
-
textreq -
phrasesreq -
optionsopt = {}
Source
# File actionview/lib/action_view/helpers/text_helper.rb, line 125
def highlight(text, phrases, options = {})
text = sanitize(text) if options.fetch(:sanitize, true)
if text.blank? || phrases.blank?
text || ""
else
match = Array(phrases).map do |p|
Regexp === p ? p.to_s : Regexp.escape(p)
end.join('|')
if block_given?
text.gsub(/(#{match})(?![^<]*?>)/i) { |found| yield found }
else
highlighter = options.fetch(:highlighter, '<mark>\1</mark>')
text.gsub(/(#{match})(?![^<]*?>)/i, highlighter)
end
end.html_safe
end
Defined in actionview/lib/action_view/helpers/text_helper.rb line 125
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActionView::Helpers::TextHelper