laiboonh

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

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

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

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.

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
nobody
How to bind a phoenix app to a specific ip address? could not find anything about that, nowhere, unfortunately, but for me this is quite...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New

Other popular topics Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36128 110
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New

We're in Beta

About us Mission Statement