Search code examples
ruby-on-railsviewpaperclip

Escaping the path/url when rendering an inline background image in Rails Views


I have the following Rails view in an ERB template where I set an inline style background image.

(The url is hard-coded for demonstration, but in reality it's generated via a paperclip attachment in my Photo model (e.g. photo.source.url(:medium))

<% url = "/system/photos/sources/000/000/008/medium/20160820_131939" %>

<div class="photo" background-image: url(<%= url %>);>
</div>

This ends up rendering the following <div>

enter image description here

Copying the above from Chrome's inspector reveals that it's being generated as key-value pairs

<div class="photo" background-image:="" url(="" system="" photos="" sources="" 000="" 008="" medium="" 20160820_131939);="">
</div>

Why does Rails do this? It seems to be trying to escape the forward slashes in the path?

  1. I tried various forms of html_safe and escaping/unescaping, but no luck.

  2. image_path and asset_path aren't applicable here because my path is generated by the paperclip gem which will correctly yield the right path in all environments.

Thanks!


Solution

  • The background-image property is CSS and needs to be within a style attribute. i.e. <div class="photo" style="background-image: url('<%= url %>');" >