Rendering live component to HTML

If I have a simple component:

defmodule MyComponent do
  use Phoenix.Component

  def greet(assigns) do
    ~H"""
    <p>Hello, <%= @name %>!</p>
    """
  end
end

How do I render that component to HTML? If I call it with MyComponent.greet("kevin"), I get:

%Phoenix.LiveView.Rendered{
  static: ["<p>Hello, ", "!</p>"],
  dynamic: #Function<0.16019880/1 in MyComponent.greet/1>,
  fingerprint: 308466332634811005649600859994209728577,
  root: true,
  caller: :not_available
}

How do I turn that Phoenix.LiveView.Rendered into HTML? I.e., I want to get the following string, but can’t figure out how:

"<p>Hello, kevin!</p>"

I ask because I am thinking of using my existing component when I do preprocessing of markdown templates, so I can just inject the HTML into the markdown template verbatim and then run it through the markdown processor. I think this is cleaner and easier to reason about than doing AST manipulations.

Phoenix.LiveView.Rendered implements the Phoenix.HTML.Safe protocol, so you can do it like this:

MyComponent.greet(%{name: "hello"})
|> Phoenix.HTML.Safe.to_iodata()
|> to_string()

References:

5 Likes

If the Markdown processor handles iodata, there’s even no need to convert to string.

1 Like