I'd like to set the title
tag in the application template, from a child view/controller in Phoenix.
The title
tag is inside the web/templates/layout/app.html.eex
template, but I have an ArticlesController
which renders to the <%= @inner %>
Coming from Rails I'd use the yield
call, but can't find its equivalent in Phoenix.
What is the right way to pass properties up to the parent template/view from its child?
You have a couple of options here. I assume you want something like content_for
in rails.
One option is to use render_existing/3
http://hexdocs.pm/phoenix/0.14.0/Phoenix.View.html#render_existing/3
Another flexible way is to use a plug:
defmodule MyApp.Plug.PageTitle do
def init(default), do: default
def call(conn, opts) do
assign(conn, :page_title, Keyword.get(opts, :title)
end
end
Then in your controller you can do
defmodule FooController do
use MyApp.Web, :model
plug MyApp.Plug.PageTitle, title: "Foo Title"
end
defmodule BarController do
use MyApp.Web, :controller
plug MyApp.Plug.PageTitle, title: "Bar Title"
end
And in your template;
<head>
<title><%= assigns[:page_title] || "Default Title" %></title>
</head>
Here we use assigns
instead of @page_title
because @page_title
will raise if the value is not set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With