How to use "link" in Phoenix

I’ve generated a resource with mix phoenix.gen.html, which then created the Movie controller and “model”. I want to be able to create a link to point to the index function in my Movie Controller, something like localhost:4000/movies.

I’ve tried with

<%= link "Movies", to: movie_path(@conn, :index), class: "btn btn-default" %> but it says: assign @conn not available in eex template.

Doing the same without @conn raises

Compiling 1 file (.ex)

== Compilation error on file web/views/layout_view.ex ==
** (CompileError) web/templates/layout/navbar.html.eex:5: undefined function movie_path/1
    (stdlib) lists.erl:1338: :lists.foreach/2
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:117: anonymous fn/4 in Kernel.ParallelCompiler.spawn_compilers/1

TLDR; I want to add a link to my movies index path, without doing <a href="/movies">. The link is going to be included in my navigation bar.

Keep in mind data from one template needs to be passed to the other template explicitly. So in the place you call render("navbar.html", ...), be sure to either pass all assigns as second argument, such as render("navbar.html", assigns), or the connection explicitly, as in render("navbar.html", conn: @conn) (preferred).

2 Likes

Phoenix is more like Django than in Ruby on Rails here - you have declare as @josevalim wrote what parameters you want to pass to your templates.

This is how I’m trying to do it in app.html.eex

<%= render("navbar.html", conn: @conn) %>

But I get the error:

Compilation error on file web/views/layout_view.ex ==
** (CompileError) web/templates/layout/navbar.html.eex:5: undefined function movie_path/1
    (stdlib) lists.erl:1338: :lists.foreach/2
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:117: anonymous fn/4 in Kernel.ParallelCompiler.spawn_compilers/1

The link in my navbar.html.eex is as follows: <%= link "Movies", to: movie_path(:index), class: "btn btn-default" %>

Note: Also tried with assigns instead of conn: @conn but it doesn’t work either.

Edit: Forgot the @conn in my link, it’s working now. Thank you guys!

1 Like