Using RoR 2.3.8
name
has the value Tiffany & Co.
This code in view:
@header_title = 'Related shops with ' + strip_tags(@shop.name)
yields result A:
#note that the & has NOT been stripped
Related shops with Tiffany & Co.
This code in view:
@header_title = strip_tags(@shop.name) + 'Related shops with '
yields result B:
#note that the & HAS been stripped
Tiffany & Co. Related shops with
I actually want Related shops with Tiffany & Co.
(i.e. convert the &
to &
)
How do I do this?
Why is it that in the second call, the &
is stripped, but not so in the first call?
Definition of striptease : an act or dance in which a person gradually removes their clothing piece by piece in a seductive or provocative manner especially to the accompaniment of music.
A guess:
@header_title = ('Related shops with ' + strip_tags(@shop.name)).html_safe
In your example the &
isn't really stripped in either case. If the string isn't marked as html safe it is being escaped by default when added to view, so &
becomes &
if you check the page source.
Alternative when @header_title
isn't html safe and you are adding it to erb view:
<%= raw @header_title %>
This 'html safeness' is related to Rails XSS protection:
Note that you should use html_safe
and raw
only when you trust the contents of the string.
--edit
Edited the answer after testing in Rails 3 console. Still don't know why the order matters there.
ruby-1.8.7-p330 :020 > ('Related shops with ' + helper.strip_tags("Tiffany & Co.")).html_safe?
=> false
ruby-1.8.7-p330 :021 > (helper.strip_tags("Tiffany & Co.") + 'Related shops with ').html_safe?
=> true
ruby-1.8.7-p330 :022 > ('Related shops with ' + helper.strip_tags("Tiffany & Co.")).html_safe.html_safe?
=> true
--edit2
Further testing.. It looks like order matters when concatenating safe and unsafe strings.
ruby-1.8.7-p330 :037 > safe = "This is html safe string".html_safe
=> "This is html safe string"
ruby-1.8.7-p330 :038 > not_safe = "This is not html safe string"
=> "This is not html safe string"
ruby-1.8.7-p330 :039 > (safe + not_safe).html_safe?
=> true
ruby-1.8.7-p330 :040 > (not_safe + safe).html_safe?
=> false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With