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
 @char_number 4

  @impl true
  def render(assigns) do
    ~H"""
    <Layouts.app flash={@flash} current_scope={@current_scope}>
       {gettext(
           "The %{count} capital letters shown above should be written...blabla"
           count: @char_number
        )}
   </.Layout.app>

I would say we could include the module attributes as fallbacks to the assigns. What do you guys think?

1 Like

Not a fan of this. More magic.

1 Like

But a lot less surprising…

Although it does cause new confusion when someone uses it as an module attribute and as an assign.

1 Like

I really liked this off the bat for the very reason of being less surprising. However, now that I think about it more does this mean any component within render would magically inherit it? They would kind of need to to keep with the “less surprising” factor this would solve, but of course I do not see that happening as that would be a pretty big shift from how things currently work.