laiboonh
How does :if heex attribute work?
Out of curiousity how does conditional rendering :if heex attribute work? I look into the web console logs and see that if condition is true the static content is passed over to the browser in s: [...]. But whenever the condition is false how does the browser know to remove the static content?
Is there something in the liveview javascript that handles this for us behind the scene?
Most Liked
LostKobrakai
That’s not completely correct. The :if condition is indeed checked on the server, but there isn’t plain html sent to the client. There’s an optimized diff sent to client, which either includes content or doesn’t. There’s more code on the client to figure out what that diff means, and the result is applied by morphdom, which takes some html and updates the DOM to match that html.
LostKobrakai
Exactly.
I think this is what the OP was asking about. The diff doesn’t contain any content and also doesn’t seem to contain any instructions for deleting content, so something on the client needs to be able to understand that such a diff means “removal of what is there”.
codeanpeace
You’re welcome! For posterity’s sake, here’s a simple naive example of what I meant by the caveat above.
defmodule MyAppWeb.SecretsLive do
use MyAppWeb, :live_view
def mount(_params, %{"current_user_id" => user_id} = _session, socket) do
user = MyApp.Accounts.get_user!(user_id)
socket =
socket
|> assign(socket, :admin, user.admin?}
|> assign(socket, :show, false) # aka hide by default
{:ok, socket}
end
def render(assigns) do
~H"""
<div :if={@admin}>
<button phx-click="toggle_secrets">Toggle Secret Stuff</button>
</div>
<div :if={@show}> **secret stuff** </div>
"""
end
# even though non-admins will not have a button that triggers this event
# a malicious non-admin user that knows about this unguarded event handler
# could directly trigger and exploit this event handler to reveal your secret stuff
def handle_event("toggle_secrets", _value, socket) do
{:noreply, assign(socket, :show, !socket.assigns.show)}
end
end
To learn more about this and the importance of authorization/permission when it comes to LiveView events, check out this guide on the Security considerations of the LiveView model.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








