Reputation: 357
I'm looking to turn all words preceeded by a # (ie #stackoverflow) into a link that when clicked through will link to the search page with the word as a query.
I tried this recently and got the right HTML being returned, but because content is automatically escaped it showed as:
This is some content <a href="search?q=something">something</a>
My question is: Is there any way to only apply html_safe to every part of the content except for these links?
Upvotes: 0
Views: 39
Reputation: 434685
If your tags are simple alphanumeric strings (i.e. nothing that needs to be HTML or URL encoded), then you could do something like this:
s = ERB::Util.html_escape(text_to_be_linkified).gsub(/#(\w+)/, '<a href="search?q=\1">\1</a>').html_safe
Then s.html_safe?
will be true and <%= ... %>
will pass the result through as-is. If you put this in a view helper, then you shouldn't need the ERB::Util.
prefix on html_escape
. If you do need to worry about URL or HTML encoding then you could modify the gsub
replacement string appropriately.
For example:
> s = ERB::Util.html_escape('<pancakes & #things').gsub(/#(\w+)/, '<a href="search?q=\1">\1</a>').html_safe
> puts s.html_safe?
true
> puts s
<pancakes & <a href="search?q=things">things</a>
Upvotes: 1