Help with Phoenix Controller

In this Phoenix controller,

def world(conn, %{"name" => name}) do
    render(conn, "world.html", name: name)

does “name” equal the first name (before the :slight_smile: in render? And the second name(after the :slight_smile: equal the name after =>?

def world(conn, %{“name” => name}) do
This matches the value for the key "name" out of the params provided by the request and binds it to the variable name.

render(conn, “world.html”, name: name)
This assigns the value of name under the key :name for rendering. name: name when the last parameter of a function is syntax sugar for [name: name], which is syntax sugar for [{:name, name}].


so “name” is the parameter itself like in get “/:name” which is binded to the => name. Then name: is the one passed to the template, which is equal to : name.

Consider this:

def world(conn, %{“name” => name_parameter}) do
    render(conn, "world.html", name: name_parameter)

def world(conn, %{“name” => my_name}) do
    render(conn, "world.html", name: my_name)

def world(conn, %{“name” => hello}) do
    render(conn, "world.html", name: hello)

Someone shared this example with me when I was trying to figure out pattern matching and it really helped.

1 Like