Sebb

Sebb

with EEx.function_from_file I can create a function from an eex-template, call it and get a rendered string back.

How can I do that with ~H?

Showing Posts 16 to 7

Sebb

Sebb OP

its me again :crazy_face:

Got heex 0.18 running with EEx.function_from_file.

EEx.function_from_file(
    :def,
    :sample,
    "sample.html.heex",
    [:assigns],
    engine: Phoenix.LiveView.TagEngine,
    caller: __ENV__,
    source: "sample.html.heex",
    tag_handler: Phoenix.LiveView.HTMLEngine
  )

Dont ask me whats going on, no idea, (and tag_handler is also not yet documented) I copied the solution from here: Using EEx.eval_string with HEEx Engine on live_view 0.18.18 - #2 by chrismccord

Sebb

Sebb OP

warning - not true, this is leex engine.
Cant get this to work with heex-engine. Using Phoenix.LiveView.HTMLEngine will complain that it has no init/1.

So I now do Phoenix.Template.compile_all which is a little odd if you want to get a function for exactly one file. But you can still do it:

if you have this template:

/foo/bar/template.html.heex

Phoenix.Template.compile_all(
  fn _ -> "template" end,
  "/foo/bar/",
  "template.html" # do not add .heex here! Its automatically added to the pattern!
)

note, that you can just give this to the engines arg:

%{md: Phoenix.Template.engines().heex, ...}

Now you can read markdown into a template! Cool.

Sebb

Sebb OP

If someone is coming here to do it the hard way (without embed_templates, eg you need more control).
This changed with LV 0.18, one now has to:

EEx.function_from_file(
          :def,
          :fun_name,
          source,
          [:assigns],
          engine: Phoenix.LiveView.Engine,
          caller: __ENV__,
          source: source
)
Sebb

Sebb OP

Just when I think: “what a mess, someone should write a macro that automatically loads the templates!”

I just didn’t know about that. Very nice, thank you.

So the whole thing looks like:

defmodule Sample do
  use Phoenix.Component

  import MyComponent

  # sample.html.heex is here
  embed_templates("templates/*")

  def render(template, assigns, path \\ nil) do
    rendered = apply(__MODULE__, template, [assigns]) |> Phoenix.HTML.Safe.to_iodata()
    if path, do: File.write!(path, rendered), else: to_string(rendered)
  end
end
LostKobrakai

LostKobrakai

Sebb

Sebb OP

Yes it works. To summarize what to do to use LV 0.18-HTMLEngine as a template engine:

# mix.exs / deps
[
  {:jason, "~> 1.4.0"},
  {:phoenix_live_view, "~> 0.18"}
]
# config.exs
import Config
# only to make Phoenix happy
config :phoenix, :json_library, Jason
# sample.ex
defmodule Sample do
  require EEx

  source = "sample.html.heex"

  EEx.function_from_file(
    :def,
    :sample,
    source,
    [:assigns],
    engine: Phoenix.LiveView.HTMLEngine,
    caller: __ENV__,
    source: source
  )

  def render(assigns) do
    sample(assigns) |> Phoenix.HTML.Safe.to_iodata() |> to_string()
  end

  def render_to_file(path, assigns) do
   # writing to a file does not need to_string
   sample(assigns)
   |> Phoenix.HTML.Safe.to_iodata()
   |> then(fn data -> File.write!(path, data) end)
  end
end
# my_component.ex
defmodule MyComponent do
  use Phoenix.Component

  def greet(assigns) do
    ~H"""
    <p>Hello, <%= assigns.name %></p>
    """
  end
end
# sample.html.heex
<MyComponent.greet name={@name} />
# iex(1)> Sample.render(%{name: "World"})
# "<p>Hello, World</p>"
n0gg1n

n0gg1n

I don’t really understand why this is necessary, but this should work:

source = "sample.eex"
EEx.function_from_file(
  :def, :sample, source, [:assigns], engine: Phoenix.LiveView.HTMLEngine, caller: __ENV__, source: source)
Sebb

Sebb OP

adding caller: __ENV__ leads to the next error:

== Compilation error in file lib/sample.ex ==
** (KeyError) key :source not found in: [file: ...
n0gg1n

n0gg1n

maybe related to this issue

try

EEx.function_from_file(
  :def, :sample, "sample.eex", [:assigns], engine: Phoenix.LiveView.HTMLEngine, caller: __ENV__)
Sebb

Sebb OP

This does not work with LV 0.18, any ideas what to do?

== Compilation error in file lib/sample.ex ==
** (KeyError) key :caller not found in: [file: "lib/sample.ex", line: 23, engine: Phoenix.LiveView.HTMLEngine]
    (elixir 1.14.2) lib/keyword.ex:595: Keyword.fetch!/2
    (phoenix_live_view 0.18.11) lib/phoenix_live_view/html_engine.ex:163: Phoenix.LiveView.HTMLEngine.init/1
    (eex 1.14.2) lib/eex/compiler.ex:295: EEx.Compiler.compile/2
    lib/sample.ex:23: (module)

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
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
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
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
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
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
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews