Template Subfolders in Phoenix

This is one of the things that annoyed me when I was starting to create apps in phoenix. Why don’t it let me create subfolders to store partials in. I want better organization of my templates.

This is an easy fix in phoenix. I didn’t come up with this but wanted to share it. I got it from here, credit goes to Chris McCord and OvermindDL1.

There are two ways to achieve this.

One is setting up a separate view and rendering it that way. This is useful for things that are shared on many different templates.

Render the other view in your html with

<%= render MyAppWeb.PartialView, "partial.html" %>

The way I was looking for with subfolders is to add the pattern option to Phoenix.View in your my_app_web.ex

use Phoenix.View, 
  root: "web/templates", 
  pattern: "**/*" 

Now I can break up a template into smaller bits. For example if I have an index page that contains a list and I want to break the table that handles the list into its own template.

Template folder would be

my_app_web\
  templates\
    user\
      partials\
        _table.html.eex
      index.html.eex

With the pattern option you can render it in your index.html with

<%= render "partials/_table.html" %>