How to use Phoenix as a library for Heex rendering, without hosting a web app

I want to use just the Heex → HTML rendering capabilities of Phoenix without hosting a web framework: why? I’m prepping for the upcoming Advent of Code and I want to build generate a table of my current progress daily as I solve puzzles. I tried using just phoenix_view but ran into issues (the docs aren’t extremely clear on how to use it in isolation). I tried copying some of the setup for Phoenix from a full Phoenix app, but I’m running into issues with modules not existing (e.g., Phoenix.Components, Phoenix.HTML, etc). Has anyone done this before? Is this possible?

Mix.install([
  {:phoenix_live_view, "~> 0.20.17"}
])

defmodule TryHeex do
  import Phoenix.Component, only: [sigil_H: 2]

  def some_func() do
    # Else you get error: (RuntimeError) ~H requires a variable named "assigns" to exist and be set to a map
    assigns = %{count: 0}

    heex = ~H"""
    <span> <%= @count %> </span>
    """

    heex
    |> Phoenix.HTML.Safe.to_iodata()
    |> IO.iodata_to_binary()
  end

  def another_func(assigns) do
    ~H"""
    My name is: <%= @name %>
    """
  end
end

TryHeex.some_func() |> IO.puts(). # 1

TryHeex.another_func(%{name: "Joe"}) |> IO.inspect() # 2

Output1:

<span> 0 </span>

Output2:

%Phoenix.LiveView.Rendered{
  static: ["My name is: ", ""],
  dynamic: #Function<0.77328309/1 in TryHeex.another_func/1>,
  fingerprint: 311051699949584893410985016783227165041,
  root: false,
  caller: :not_available
}
6 Likes

You only need phoenix_live_view to render HEEx as mentioned above, but if you want an easy way to get all of the necessary deps to use Phoenix without mix phx.new, you can also check out the recently-announced Phoenix Playground:

https://hexdocs.pm/phoenix_playground/readme.html

1 Like

This works perfectly, thanks for sharing!

Appreciate the share. I’ll give this a look!

1 Like