How to check if a template exists, in a controller?

In a controller:

Phoenix.Controller.render(conn, "some template name.html")

I want to check if a default_template.html exists, and if not, render a custom_template.html.

How to check if a template exists? Preferably without raising an exception, with no penalty to performance.

Hey @romik

Looks like you can use Phoenix.View.render_existing/3
https://hexdocs.pm/phoenix/Phoenix.View.html#render_existing/3

eg:

Phoenix.View.render_existing(MyAppWeb.UserView, "non-existing.html")
# => nil
1 Like

No, it doesn’t look like it

Hi @romik this is not a helpful reply. Please elaborate about the issue you are having, and provide some context around the code you are calling, and what you are trying to do overall.

5 Likes

In a controller:

Phoenix.Controller.render(conn, "some template name.html")

I want to check if a default_template.html exists, and if not, render a custom_template.html .

How to check if a template exists? Preferably without raising an exception, with no penalty to performance.

Can you please explain the “why” you want it, rather then the “what” you want?

I think this is an XY problem, and there could be a much better solution to your problem then checking the existence of a template in the controller.

In my opinion the controller shouldn’t even be aware of templates at all… The view should decide what and how to render.

1 Like

In my case I need is what I’ve described.

Why do you think you need it exactly that way?

There are a few ways of knowing if a template exists, but besides render_existing all of them are undocumented private api. render_existing is only available within views not within controllers. Therefore, no this cannot be done from the controller level.

I’m not sure if this is the same person (different usernames are used), but this conversation came up on Reddit about a month ago. I only bring this up because both posters seem to have the same attitude towards people trying to help them.

1 Like

I have already noticed, and will take care it does not go further in this direction…

1 Like

That’s it.