Rendering Views outside of Actions with Action View

In a recent post, we took a look at using Rails 5's new ActionController.renderer to render a template outside of a controller action.

This approach offers us a lot of flexibility, but it might be overkill for some situations. In the feature for which I first looked at ActionController.renderer, I render a template in order to capture the HTML, convert it into Markdown and write that Markdown to README.md files to be posted to GitHub using the GitHub API.

In this case, I don't need to use any of my application's layouts (i.e. any layouts containing navbars, footers, etc). I only need to grab the HTML that comprises a given template. Using ActionController.renderer renders the template with the layout.

If only there was a way to render a template without the layout...

Luckily for us (and anyone not using Rails 5, for that matter), there is!

View Rendering with Action View

Let's assume we're rendering the show page for a blog post:

< h1 > <%= @post.title %> < /h1 >
< p > <%= @post.content %> < /p >

To render this template with Action View, we go through the following steps:

  • Create a new instance of ActionView::Base:
view = ActionView::Base.new(ActionController::Base.view_paths, {})
  • Assign the instance variable, @post, to our view instance:
view.assign(schedule: @schedule)
  • Render the view with the ActionView#render method:
view.render(file: 'posts/show.html.erb')

subscribe and never miss a post!

Blog Logo

Sophie DeBenedetto

comments powered by Disqus
comments powered by Disqus