Last active
July 7, 2016 01:41
-
-
Save net/8cf31d83d44593e54fe6c068ef88855c to your computer and use it in GitHub Desktop.
Render Phoenix templates inside other templates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule YourApp.RenderIn do | |
@moduledoc """ | |
Renders a block inside another template. | |
## Usage | |
# template/page/page.html.eex | |
<div class="container"> | |
<%= @yield %> | |
</div> | |
# template/page/index.html.eex | |
<%= render_in "page.html", fn -> %> | |
<p>Hello world!</p> | |
<% end %> | |
# Result | |
<div class="container"> | |
<p>Hello world!</p> | |
</div> | |
## With assigns | |
An assigns keyword list can be passed in before the function parameter. | |
# template/user/page.html.eex | |
<h1><%= @header %></h1> | |
<%= @yield %> | |
</div> | |
# template/user/show.html.eex | |
<%= render_in "page.html", header: "User", fn -> %> | |
<p>Hello world!</p> | |
<% end %> | |
## With a view module | |
A view module can be specified. | |
render_in SharedView, "page", fn -> ... end | |
render_in SharedView, "page", assigns, fn -> ... end | |
""" | |
defmacro __using__(_opts) do | |
quote do | |
def render_in(template, fun), do: render_in(template, %{}, fun) | |
def render_in(template, assigns, fun) when is_bitstring(template) do | |
render template, Map.put(assigns, :yield, fun.()) | |
end | |
def render_in(module, template, fun) do | |
render_in(module, template, %{}, fun) | |
end | |
def render_in(module, template, assigns, fun) do | |
render module, template, Map.put(assigns, :yield, fun.()) | |
end | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Use in your web/web.ex: | |
defmodule YourApp.Web do | |
... | |
def view do | |
quote do | |
... | |
use YourApp.RenderIn | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment