Exposing a helper/custom function to Live EEx templates

Presently using Elixir 1.11.3 and Phoenix 1.5.8

I had done a LiveView tutorial by from The Pragmatic Studio about a half year ago and defined private functions that could be used inside a leex template without having to do anything else. I could invoke this function inside the leex template without any additional set-up, but now this does not work. I sifted around the LiveView documentation to see if there was some documentation on this, but didn’t come across any.

I’m wondering if this is has been deprecated in favor of using assigns instead. That’s my best guess. Here’s what I was doing before:

defmodule LiveViewStudioWeb.SortLive do
  use LiveViewStudioWeb, :live_view

  defp sort_link(socket, text, sort_by, options) do
    text = if sort_by == options.sort_by, do: text <> emoji(options.sort_order), else: text
    live_patch(text,
      to:
        Routes.live_path(
          socket,
          __MODULE__,
          sort_by: sort_by,
          sort_order: toggle_sort_order(options.sort_order),
          page: options.page,
          per_page: options.per_page
        )
    )
  end
end

# inside the leex template
<%= sort_link(@socket, "Days Until Expires", :days_until_expires, @options) %>

Should I just be creating a :sort_link assign? If not, how can I expose this function?

Works fine for me I can call my View’s functions in an external template. What error do you get? Maybe you need to import something to use live_redirect?

It should works I think. What did the compiler complain?

Also @Ljzn

Sorry, forgot to include the error as well. It’s just a compilation error, which doesn’t make sense. I’ve tried making it public and the arity is also correct, but the trace doesn’t give me enough to work with without having to dig through the source code for leex.

Compiling 1 file (.ex)

== Compilation error in file lib/live_view_studio_web/live/sort_live/index.ex ==
** (CompileError) lib/live_view_studio_web/live/sort_live/index.html.leex:22: undefined function sort_link/4
    (elixir 1.11.3) src/elixir_locals.erl:114: anonymous fn/3 in :elixir_locals.ensure_no_undefined_local/3
    (stdlib 3.14) erl_eval.erl:680: :erl_eval.do_apply/6
    (elixir 1.11.3) lib/kernel/parallel_compiler.ex:314: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/7

Looks like the error is from lib/live_view_studio_web/live/sort_live/index.ex, is it the filename of LiveViewStudioWeb.SortLive module?

Appreciate the help – I figured it out. Rookie mistake. I copied the function over from the demo but I had changed the arity in my new project, so the trace was right – that it couldn’t find that function. I didn’t realize it until my sanity check prefixing the fully qualified module in front of the function then ran mix compile and got the hint asking whether I meant the same function with an arity of 3 (not 4). Major face palm!

1 Like