instance method
highlight
Ruby on Rails 3.0.20
Since v2.2.3Signature
highlight(text, phrases, *args)
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 ‘<strong class=“highlight”>\1</strong>’)
Examples
highlight('You searched for: rails', 'rails') # => You searched for: <strong class="highlight">rails</strong> 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>
You can still use highlight with the old API that accepts the highlighter as its optional third parameter:
highlight('You searched for: rails', 'rails', '<a href="search?q=\1">\1</a>') # => You searched for: <a href="search?q=rails">rails</a>
Parameters
-
textreq -
phrasesreq -
argsrest
Source
# File actionpack/lib/action_view/helpers/text_helper.rb, line 111
def highlight(text, phrases, *args)
options = args.extract_options!
unless args.empty?
options[:highlighter] = args[0] || '<strong class="highlight">\1</strong>'
end
options.reverse_merge!(:highlighter => '<strong class="highlight">\1</strong>')
if text.present? && phrases.present?
match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')
text = text.to_str.gsub(/(#{match})(?!(?:[^<]*?)(?:["'])[^<>]*>)/i, options[:highlighter])
end
text = sanitize(text) unless options[:sanitize] == false
text
end
Defined in actionpack/lib/action_view/helpers/text_helper.rb line 111
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActionView::Helpers::TextHelper