Phoenix.View.render_existing
render_existing
, go back to Phoenix.View module for more information.
Renders a template only if it exists.
Same as render/3
, but returns nil
instead of raising.
This is often used with Phoenix.Controller.view_module/1
and Phoenix.Controller.view_template/1
, which must be
imported into your views. See the "Examples" section below.
Examples
Consider the case where the application layout allows views to dynamically render a section of script tags in the head of the document. Some views may wish to inject certain scripts, while others will not.
<head>
<%= render_existing view_module(@conn), "scripts.html", assigns %>
</head>
Then the module under view_module(@conn)
can decide to provide scripts with
either a precompiled template, or by implementing the function directly, ie:
def render("scripts.html", _assigns) do
~E(<script src="file.js"></script>)
end
To use a precompiled template, create a scripts.html.eex
file in the templates
directory for the corresponding view you want it to render for. For example,
for the UserView
, create the scripts.html.eex
file at your_app_web/templates/user/
.
Rendering based on controller template
In some cases, you might need to render based on the template.
For these cases, Phoenix.Controller.view_template/1
can pair with
render_existing/3
for per-template based content, ie:
<head>
<%= render_existing view_module(@conn), "scripts." <> view_template(@conn), assigns %>
</head>
def render("scripts.show.html", _assigns) do
~E(<script src="file.js"></script>)
end
def render("scripts.index.html", _assigns) do
~E(<script src="file.js"></script>)
end