We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Phoenix LiveView and HEEx (HTML Embedded Elixir) are powerful tools in the Elixir ecosystem for building interactive web applications. They allow developers to create dynamic HTML components that can be rendered server-side or updated on the client. In this post, we'll explore how to render a HEEx component directly in code, using a simple example.
Defining the component
To get started, we'll first define a basic HEEx component that greets a user by their name. HEEx components are defined inside a module, and you can easily create reusable elements in your templates.
Here's how you can define a simple hello
component:
defmodule MyAppWeb.Components do
use Phoenix.Component
attr :name, :string, required: true
def hello(assigns) do
~H"""
<div>
<h1>Hello, <%= @name %>!</h1>
</div>
"""
end
end
This module defines a hello
function that takes in assigns
, which is a map containing any attributes passed to the
component. The attr
macro declares the expected attributes, and in this case, we require a :name
string. Inside the
component, we use HEEx syntax to render a div
with a greeting.
Rendering the component in code
In most cases, HEEx components are rendered in templates. However, you can also render them programmatically in your
code if needed. For example, imagine you want to render the hello
component from a controller or another part of your
application logic.
Here's how you can render the component in code:
component = MyAppWeb.Components.hello(%{name: "world"})
component
|> Phoenix.HTML.Safe.to_iodata()
|> IO.iodata_to_binary()
|> IO.puts()
In this snippet:
- We call the
hello
function, passing a map with thename
attribute set to"world"
. - The result is then piped into
Phoenix.HTML.Safe.to_iodata/1
to convert the component's rendered content into IO data, which is a more efficient representation of strings in Elixir. - The IO data is converted into a binary (a standard string) using
IO.iodata_to_binary/1
. - Finally, we print the resulting string with
IO.puts/1
, which outputs the HTML to the console.
Conclusion
Rendering HEEx components in code is a useful technique for scenarios where you need to dynamically generate HTML outside of traditional templates. By following the steps above, you can easily define and render Phoenix components programmatically.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.