Last Updated: April 04, 2020
·
2.403K
· michaelcarter

Rendering rails partials as their HTML source

Sometimes we'll want to do things like display code snippets in our rails views. Traditionally, we'd do this by escaping the entities of our HTML and just putting it between <pre> tags, but rails affords us a better way through the use of the htmlentities gem and a clever helped method.

First off, add the htmlentities gem to your Gemfile:

gem 'htmlentities'

Next, we can wrap our views existing render method and get it to render the HTML of the view instead. Put this in your application_helper.rb file:

def render_source args={}
    @html_encoder ||= HTMLEntities.new
    raw(@html_encoder.encode(render args))
end

In my project I have a partial called _signup_snippet.html.erb, I can now render this in my a view cleanly with the following:

<pre>
  <%= render_source :partial => "signup_snippet" %>
</pre>

Easy! I've not tried this with anything but rendering partials, but I expect it'll work in a similar way with the other options render supports, more info on the rubyonrails.org guide page.