Implement Rails Views with Common Code

Proper structuring of views in an application is important. It helps minimize code redundancy. For components you can use partials. If the common code applies in the scale of layouts its best you use nested layouts. In addition to using nested layouts, you have the option to use partials that accept blocks.

Nested Layouts

Nested layouts are best when the common code applies in a layout level. For example think about a blog section. It will be different from the main layout in a way there will be a sidebar and a header. In ways layouts/application.html.slim will have additions to it. This is when you should use nested layouts.

You will have to modify your layouts/application.html.slim to accept a content_for block. This is where we will add the nested layouts content in to.

    = content_for?(:content) ? yield(:content) : yield

Then you can write a nested layout as follows. Lets say it is layouts/blog.html.slim.

- content_for :content do
    h1 My Cool Blog
    = yield
    = render 'layouts/blog/sidebar'

= render template: 'layouts/application'

Partials Accepting Blocks

The other way to share layout code is through partials that accept blocks. Think about a page referencing a blog post. Rather than just having a link, you make a little drama adding the blog title, featured image etc.

In the page, we desire some thing like…

/ views/pages/products/web-crawlers-and-scrapers.html.slim
h1 Web Crawlers and Scrapers
p Lorem ipsum...
p Lorem ipsum...

= render partial: 'blogs/embed', locals: { blog: Blog.find(1) } do
    li Point 1
    li Point 2
  p Lorem ipsum...

Here we can customize each embed in the page by adding some extra slim to describe the context.

In the blogs embed view partial, we can do some thing like this.

/ views/blogs/_embed.html.slim
h3 blog.title
= image_tag blog.image.url
= yield

While this is a basic example, I believe you get the point.


Rails allows you to neatly structure your views reducing code duplication. While it is easy I have seen some projects with views that can only be described as a nightmare. A word of advice, don’t leave them a all over the place and and DRY (do not repeat your self) things up.

While I believe modern applications should be built separately as an API (Rails API, Grape or in node LoopBack) and client-side app using some thing like React JS or Angular, the Rails view layer will stay alive for a good 10 years to come. Hence my contribution on the topic.