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" ->
_ ->

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

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

About the author

Add comment

Leave a Reply

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

By shawn

Other Things