Accessing module attributes in HEEx?

I want to use a module attribute in HEEx code, like following code:

defmodule MyView do
  use Phoenix.LiveView
  @test "Test!"

  def render(assigns) do
    ~H"""
    <div>{@test}</div>
    """
  end
end

I want @test will be interpreted as "Test!", the module attribute, but the compiler tries to read assigns.test and occurs error. Is there any convenient way to use module attributes in the HEEx?

Inside a function you can simple interpolate string:

"some #{@test} string"

Inside template you need to assign module attribute to assigns.

You can add a helper function which returns this module attribute and use it in the template. Module attributes are not accessible in templates or outside of the modules in which they are defined.

5 Likes