Skip to content

Instantly share code, notes, and snippets.

@cigrainger
Created May 15, 2024 10:59
Show Gist options
  • Save cigrainger/0eee54068e85c63df1c6a5407918d7e3 to your computer and use it in GitHub Desktop.
Save cigrainger/0eee54068e85c63df1c6a5407918d7e3 to your computer and use it in GitHub Desktop.
Mix.install([
{:phoenix_playground, "~> 0.1.0"}
])
defmodule ContainerLive do
use Phoenix.LiveView
def mount(_params, _session, socket) do
{:ok, assign(socket, view: DemoLive)}
end
def render(assigns) do
~H"""
<%= live_render(@socket, @view, id: "#{@view}-view") %>
<button phx-click="swap_view">Swap view</button>
"""
end
def handle_event("swap_view", _params, socket) do
{:noreply, update(socket, :view, &swap_view/1)}
end
defp swap_view(DemoLive), do: PlaceholderLive
defp swap_view(PlaceholderLive), do: DemoLive
end
defmodule PlaceholderLive do
use Phoenix.LiveView
def mount(_params, _session, socket) do
{:ok, assign(socket, count: 0)}
end
def render(assigns) do
~H"""
<h1>Live View 2</h1>
<button phx-click="inc">+</button>
<button phx-click="dec">-</button>
<span><%= @count %></span>
<style type="text/css">
body { padding: 1em; }
</style>
"""
end
def handle_event("inc", _params, socket) do
{:noreply, assign(socket, count: socket.assigns.count + 1)}
end
def handle_event("dec", _params, socket) do
{:noreply, assign(socket, count: socket.assigns.count - 1)}
end
end
defmodule DemoLive do
use Phoenix.LiveView
def mount(_params, _session, socket) do
{:ok, assign(socket, count: 0)}
end
def render(assigns) do
~H"""
<h1>Live View 1</h1>
<span><%= @count %></span>
<button phx-click="inc">+</button>
<button phx-click="dec">-</button>
<style type="text/css">
body { padding: 1em; }
</style>
"""
end
def handle_event("inc", _params, socket) do
{:noreply, assign(socket, count: socket.assigns.count + 1)}
end
def handle_event("dec", _params, socket) do
{:noreply, assign(socket, count: socket.assigns.count - 1)}
end
end
PhoenixPlayground.start(live: ContainerLive)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment