Upgrading Phoenix 1.5's render_existing

Apr 30, 2020

In Phoenix 1.5.0 if you migrated your Phoenix app to use the newer way of rendering a root layout by adding plug :put_root_layout, {MyAppWeb.LayoutView, :root} and you had been using render_existing as a way to dynamically call a render function in your view like so.

<%= render_existing(@view_module, "script." <> @view_template) %>

You probably noticed that @view_module and @view_template would return MyAppWeb.LayoutView and :root and thus caused an issue with your dynamic js tags.

If you were to look in your conn you would likely notice that the private has a two values that would be the preferred values of the view_module and view_template. Luckily, the Phoenix.Controller has two helper methods view_module/1 and view_template/1 which both look to the conn’s private to get at the values respectively. This means we can just update our call to render_existing/3 to use these helper vs using the assigns values like so.

<%= render_existing(view_module(@conn), "script." <> view_template(@conn)) %>

Note: view_module was already being imported via the use MyAppWeb, :view macro, you will need to include the view_template/1

import Phoenix.Controller,
        only: [get_flash: 1, get_flash: 2, view_module: 1, view_template: 1]

It should also be noted that @view_module is to be deprecated and removed come Phoenix 1.6.0

Now your dynamic render_existing/3 use should be working again like it did before you migrated.

Photo by: Ed Schipul