cahill

cahill

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__

Showing Posts 1 to 9

LostKobrakai

LostKobrakai

The documentation includes alternatives:

cahill

cahill OP

The function_exported? alternative is not working. __MODULE__.module_info(:exports) does not list :index

This is how I understand the suggested alternative, but no joy:

if function_exported?(__MODULE__, :index, 1) do
  render(__MODULE__, "index.html", assigns)
else
  render("default_index.html", assigns)
end
LostKobrakai

LostKobrakai

It’s not working because functions and templates are different things. Phoenix.Template does not create individual functions per template, so you cannot use function_exported? to check if a certain template is available. The documentation shows not only the function_exported? code, but also a function that’s being checked for. This seems to be in line with the push to more function components using heex.

cahill

cahill OP

Ah, that makes sense. Is there any way to check for template existence? Or is using the deprecated function my only option?

Alternatively, how would I switch from templates to function components?

AlchemistCamp

AlchemistCamp

Unfortunately those really aren’t alternatives for what the OP is encountering (or what I am in my apps). It’s an alternative for a much narrower use case.

I’m still looking for a better solution, but will share what I’ve got.

AlchemistCamp

AlchemistCamp

In my site, there’s an embedded VuePress site (for a book that’s only loosely tied to the rest of the site). VuePress generates HTML files that I convert into Elixir templates upon each build. As a result, the Phoenix app needs to be able to conditionally render templates if they’ve been built or redirect to a 404 if they haven’t.

Here’s what I’m doing it the relevant controller:

  def page(conn, %{"page" => pages}) do
    template = Enum.join(pages, "/")

    if page_exists?(template) do
      conn
      |> put_layout({CampsiteWeb.LayoutView, :book})
      |> render(template, title: template)
    else
      Logger.warn("missing_template: #{inspect template}")
      conn
      |> put_status(404)
      |> render("404.html", message: "Page not found")
    end
  end

  defp page_exists?(name) do
    prefix = case Application.get_env(:campsite, :mix_env) do
      :prod -> "../../builds/campsite/"
      _ -> ""
    end
    File.exists?(prefix <> "lib/campsite_web/templates/potion/#{name}.eex") ||
    File.exists?(prefix <> "lib/campsite_web/templates/potion/#{name}.heex") ||
    File.exists?(prefix <> "lib/campsite_web/templates/potion/#{name}.leex")
  end

Note that this solution depends on the existence of template files in a specific location! In my case that location is different in prod than it is in dev, so I’ve added a mix_env key to the Application environment.

It’s not an ideal solution but it works for this use case as well as for a couple of other CMS-type apps where users need to be able to add and remove templates in content directories without changing controller or router code.

al2o3cr

al2o3cr

This sounds like the place to improve; your current process uses the template files both as templates and as metadata about which templates are defined. What if it instead output both template files and some sort of compile-able metadata?

For instance, you could generate a file like (name is terrible, sorry):

defmodule TemplateExistence do
  def template_exists?("foo.html"), do: true
  ...
  def template_exists?(_), do: false
end

This way the metadata about which templates exist and the templates are both embedded into the compiled BEAM files, and the template files themselves aren’t needed post-compilation.

AlchemistCamp

AlchemistCamp

I should clarify. VuePress outputs HTML files. I “convert” those to Elixir templates by renaming the files from whatever.html to whatever.html.eex. That’s it, and it “just works”.

I’m not dynamically outputting defmodule, def or any Elixir syntax and doing so would be both a lot more effort and a source of potential bugs. It would move the process from a quick integration between my static site generator and a Phoenix app into a larger engineering project that I don’t currently have the resources for.

Your suggestion is very straightforward as far as generating a .ex Elixir file goes, but it’s also replicating the same information I can now reliably get (with my current deployment strategy) by looking at the filesystem.

If I couldn’t rely on the filesystem, then dynamically generating one or more .ex files might be the only way.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews