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?

First Post!

milangupta

milangupta

The processing is happening on the server side ..
The beauty of this is security ..

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.

Last Post!

kevinschweikert

kevinschweikert

The difference would be that the new syntax with the inline if works only if you want to interpolate a value. The block syntax has the added benefit, that you can write additional HTML like this for example.

<%= if @category_id do %>
   <span class="text-blue-400">{gettext("Edit Category")}</span>
 <% else %>
   <span class="text-red-600">{gettext("New Category")}<span>
 <% end %>

This wouldn’t work when you write it like this:

{if @category_id, do: "<span class=\"text-blue-400\">#{gettext("Edit Category")}</span>", else: "<span class=\"text-red-600\">#{gettext("New Category")}<span>"}

As you can see, you would have to write it as a string and then it wouldn’t be handled as HTML

Where Next?

Popular in Questions Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

Other popular topics Top

JeremM34
Hello, how can I check the Phoenix version ? Thanks !
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
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 40165 209
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 44265 214
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement