content_for in Phoenix

Disclaimer: I’m very new at both Elixir and Phoenix so the below might be horrible. ┬áIf it is let me know in the comments.

Problem: I need content_for in Phoenix

Solution: render_existing

For this example we’ll be using the page controller and the app.html.eex layout to add breadcrumbs to the top of the page.

1. In app.html.eex where you want the breadcrumbs add
<%= raw render_existing view_module(@conn), "breadcrumbs.html", assigns %>

2. In web/views/page_view.ex add the following
def render("breadcrumbs.html", assigns) do
case assigns[:action] do
"index" ->
"<li>Dashboard</li>"
_ ->
""
end
end

3. In web/controllers/page_controller.ex change index as follows
def index do
conn
|>assign(:action, "index")
|>render "index.html"
end

And you’re done. Just add conditions to the view anytime you want something different shown and update the render call on the action.

Leave a reply:

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Site Footer

Sliding Sidebar

Other Things