{"id":7515,"date":"2018-05-16T17:53:04","date_gmt":"2018-05-16T20:53:04","guid":{"rendered":"http:\/\/blog.plataformatec.com.br\/?p=7515"},"modified":"2018-05-17T16:50:36","modified_gmt":"2018-05-17T19:50:36","slug":"nested-layouts-with-phoenix","status":"publish","type":"post","link":"http:\/\/blog.plataformatec.com.br\/2018\/05\/nested-layouts-with-phoenix\/","title":{"rendered":"Nested Layouts With Phoenix"},"content":{"rendered":"

Over the last few weeks, we have been building a web application in one of our clients and ended up duplicating some template code. These new pages had something in common between them, but not with the rest of the application. We needed an inner layout to reuse the template code between these pages, however, Phoenix doesn’t come with this feature. In this post, you’ll learn how you can build nested layouts in Phoenix and when you should use them.<\/p>\n

Why are they useful?<\/h2>\n

Inner (or nested) layouts are useful to reuse template code when you have subsections on your website. Usually, in Phoenix applications, we have \/templates\/layout\/app.html.eex<\/code> that shares template code between all pages. For example:<\/p>\n

\"Example<\/p>\n

 <\/p>\n

In the example above, we want to reuse the application logo, title, and navigation menu across all pages. We can solve that by using the Phoenix default layout and it works great. However, sometimes you need to create a new website section inside the parent layout. For example, imagine we want to add a help section to our Phoenix website. Look at the image below:<\/p>\n

\"Inner<\/p>\n

We still want to reuse the layout header across all pages, but we also want to reuse the left navigation and main content layout in all pages inside the help section. Let’s see how we can do that using Phoenix.<\/p>\n

The Inner Layout Solution<\/h2>\n

I tried some solutions by looking at some examples online. After discussing with the Plataformatec team, we came up with an approach that’s very simple and extensible, thanks to Phoenix explicit layout rendering. The solution works like this:<\/p>\n

\"layout<\/p>\n