Last active
May 20, 2024 02:44
-
-
Save kimihito/fe54c499e8a343db0b95756bae5f1e40 to your computer and use it in GitHub Desktop.
htmx plugs ( from https://cosmicrose.dev/blog/htmx-elixir/ )
This file contains 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
# create myapp_web/plugs/htmx.ex | |
defmodule MyAppWeb.Plugs.Htmx do | |
import Plug.Conn | |
import Phoenix.Controller, only: [put_root_layout: 2, put_layout: 2, root_layout: 1, layout: 1] | |
@behaviour Plug | |
@impl true | |
def init(opts), do: opts | |
@impl true | |
def call(conn, _opts) do | |
detect_htmx_request(conn) | |
htmx_layout(conn) | |
end | |
defp detect_htmx_request(conn) do | |
if get_req_header(conn, "hx-request") == ["true"] do | |
assign(conn, :htmx, %{ | |
request: true, | |
boosted: get_req_header(conn, "hx-boosted") != [], | |
current_url: List.first(get_req_header(conn, "hx-current-url")), | |
history_restore_request: get_req_header(conn, "hx-history-restore-request") == ["true"], | |
prompt: List.first(get_req_header(conn, "hx-prompt")), | |
target: List.first(get_req_header(conn, "hx-target")), | |
trigger_name: List.first(get_req_header(conn, "hx-trigger-name")), | |
trigger: List.first(get_req_header(conn, "hx-trigger")) | |
}) | |
else | |
conn | |
end | |
end | |
defp htmx_layout(conn) do | |
if get_in(conn.assigns, [:htmx, :request]) do | |
conn = put_root_layout(conn, html: false) | |
if conn.assigns.htmx[:boosted] or conn.assigns.htmx[:history_restore_request] do | |
put_layout(conn, layout(conn)) | |
else | |
put_layout(conn, html: false) | |
end | |
else | |
conn | |
|> put_root_layout(root_layout(conn)) | |
|> put_layout(layout(conn)) | |
end | |
end | |
end |
This file contains 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 MyAppWeb.Router do | |
# ... | |
alias MyAppWeb.Plugs | |
pipeline :browser do | |
plug :accepts, ["html"] | |
# .... | |
plug Plugs.Htmx | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment