Using sigil_E inside of a macro

I’d like to use the ~E sigil inside of a macro. For some reason the assigns variable is not accessible:

defmacro __using__(_opts) do
  quote do
    use AppWeb, :view

    def render("index.html", assigns) do
      ~E"""
      <%= @test %>
      """
    end
  end
end

Result:

expected “assigns” to expand to an existing variable or be part of a match

Writing the render/2 function directly into a view works fine. Is there a way to make this work?

Thanks!

1 Like

I think you’ll have to set unquote: false to defer expansion. Therefore:

defmacro __using__(_opts) do
  quote unquote: false do
    use AppWeb, :view

    def render("index.html", assigns) do
      ~E"""
      <%= @test %>
      """
    end
  end
end
2 Likes

Variables defined inside a macro that their own context, so they don’t conflict with user variables. You can force it to be the user variable by using var!:

    def render("index.html", var!(assigns)) do
5 Likes