简体   繁体   中英

Phoenix macro to render template if it exists in module

I have a macro that renders a template like index.html.eex if it exists in the __MODULE__ that the macro is used in. Otherwise it falls back to index.html.eex in the macro:

render_existing(__MODULE__, "index.html", assigns) || render(MacroView, "index.html", assigns)

This allows some views to be customized with more code, while most views use a standard template.

After upgrading the Phoenix 1.6, render_existing is deprecated. What is the best way to conditionally render a template in __MODULE__ if it exists? It doesn't seem like it's possible to resolve a file path from __MODULE__

Although I don't like it, you can use try, rescue like so, maybe?

try do
  __MODULE__.render("index.html", assigns)
rescue
  Phoenix.Template.UndefinedError -> MacroView.render("index.html", assigns)
end

It doesn't seem like it's possible to resolve a file path from MODULE

You should have access to the __MODULE__ file path using __ENV__.file() . Maybe you can then figure out yourself if the template file exists within a helper function?

Also, last but not least:

No luck. :index is not listed in MODULE .module_info(:exports)

Did you look at the attributes key? It lists all the existing templates for a given view, within the keys :external_resources .. But it might be difficult to parse.

Anyway, good luck, I found your use case interesting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM