Highlighting Text in Rails
Presumably you've seen those Web 2.0 sites that highlight random words in the marketing text to draw your attention. A little-known view helper in Rails makes this sort of thing trivial. For example, you can combine this markup in your view:
[sourcecode language='ruby']
When you start 'Riding the Rails' you'll never go back.",
"Rails") %>
[/sourcecode]
With this bit of CSS:
[sourcecode language='css']
.highlight { background:#ff0; }
[/sourcecode]
And you get this result:

Easy enough. But wait, there's more! You can specify an entire array of words and phrases to highlight:
[sourcecode language='ruby']
[/sourcecode]
Even better,
[sourcecode language='ruby']
:highlighter => '\1') %>
[/sourcecode]
This ability to insert arbitrary surrounding markup makes
[sourcecode language='ruby']
:highlighter => '<a href="/users/%5C1">\1</a>) %>
[/sourcecode]
It's worth taking a dip into ActionView::Helpers occasionally to see what other bits of functionality are lurking that you've forgotten about.
[sourcecode language='ruby']
When you start 'Riding the Rails' you'll never go back.",
"Rails") %>
[/sourcecode]
With this bit of CSS:
[sourcecode language='css']
.highlight { background:#ff0; }
[/sourcecode]
And you get this result:
Easy enough. But wait, there's more! You can specify an entire array of words and phrases to highlight:
[sourcecode language='ruby']
[/sourcecode]
Even better,
highlight
supports a :highlight
option, which lets you specify a custom string to use for highlighting. The token \1
will be replaced with the text to be highlighted. This lets you change the HTML markup:[sourcecode language='ruby']
:highlighter => '\1') %>
[/sourcecode]
This ability to insert arbitrary surrounding markup makes
highlight
more flexible, if you let yourself think out of the box:[sourcecode language='ruby']
:highlighter => '<a href="/users/%5C1">\1</a>) %>
[/sourcecode]
It's worth taking a dip into ActionView::Helpers occasionally to see what other bits of functionality are lurking that you've forgotten about.