How to display a value in a template?

Hello! Sorry for the dumb question but how do I display a variable in template. Let’s say I have an input in template and a button for submitting it. Once submitting, the value that I entered in my input passes to a controller. I was able to get the value through the controller and my problem is how do I display it on the same template?

do you want to show the value in the template your controller action returns? if so then the you need to pass your value in teh render/3 function, for example:

Given a controller:

defmodule MyAppWeb.MyController do
  use MyAppWeb, :controller


  def new(conn, params = %{"value" => my_value}) do
   # do your stuff
   render(conn, "new.html", value: my_value)
  end

end

render/3 accepts a keyword list or a map as last argument, so anything you need to send to template you put there with a key, so on you template you can access it as

<span><%= @value %></span>

btw, there is no such thing as dumb question! :smile:

3 Likes

I gott the error:

assign @value not available in eex template.

Do you mind sharing your controller and template code?

2 Likes

Most of the times, try restarting mix phx.server.

I know this is quite old, but I have this exact same problem, and I’m stuck.

def new(conn, _params) do
      changeset = Administration.change_admin(%Admin{})

      admin_roles = [1,2,3]

      render(conn, "new.html", changeset: changeset, admin_roles: admin_roles)
    end

Then in html <%= admin_roles %>

Error: variable "admin_roles" does not exist
`

UPDATE: realized I need @admin_roles in template

I’m trying to pass a “users” variable but I’m receiving the error

KeyError <small>at GET</small> <small>/agendas/new</small>

key :users not found in: %{
  action: "/agendas",
  __changed__: nil,
  __given__: %{
    action: "/agendas",
    __changed__: nil,
    changeset: #Ecto.Changeset<
      action: nil,
      changes: %{},
      errors: [
        data: {"can't be blank", [validation: :required]},
        hora: {"can't be blank", [validation: :required]}
      ],
      data: #Vacinacao.Agendas.Agenda<>,
      valid?: false
    >
  },
  changeset: #Ecto.Changeset<
    action: nil,
    changes: %{},
    errors: [
      data: {"can't be blank", [validation: :required]},
      hora: {"can't be blank", [validation: :required]}
    ],
    data: #Vacinacao.Agendas.Agenda<>,
    valid?: false
  >
}

Hello and welcome, please use 3 ` to format your code. I did the change this time.

You don’t show how You try to pass the users to the template. You should, because we don’t know your code