LiveView function component assigns

Hello,
I’m new to Pheonix and Liveview and I was following some tutorials on LiveView. There I found this code.

def day(%{index: index, current_path: current_path, date: date, time_zone time_zone} = assigns) do
    date_path = build_path(current_path, %{date: date})
    disabled = Timex.compare(date, Timex.today(time_zone)) == -1
    weekday = Timex.weekday(date, :monday)

    class =
      class_list([
        {"grid-column-#{weekday}", index == 0},
        {"content-center w-10 h-10 rounded-full justify-center items-center flex", true},
        {"bg-blue-50 text-blue-600 font-bold hover:bg-blue-200", not disabled},
        {"text-gray-200 cursor-default pointer-events-none", disabled}
      ])

    assigns =
      assigns
      |> assign(disabled: disabled)
      |> assign(:text, Timex.format!(date, "{D}"))
      |> assign(:date_path, date_path)
      |> assign(:class, class)

    ~H"""
    <%= live_patch to: @date_path, class: @class, disabled: @disabled do %>
      <%= @text %>
    <% end %>
    """
  end

In here author assigned every new value that he uses in the template to “assigns” variable. I did it without assigning them and it worked.

~H"""
  <%= live_patch to: date_path, class: class, disabled: disabled do %>
    <%= text %>
  <% end %>
"""

without assigning these values can cause any difference? Is assigning them considered good practice or it’s preference?

It’s essential for LVs ability to track changes for its diffing algorithm. 0.18 does even issue a warning about using variables directly in a template instead of the @… macro.

2 Likes