How to Render Dynamic Variables in a Phoenix LiveView

From ElixirBlocks
Jump to: navigation, search

Before You Begin


Installing Phoenix

This article assumes that you have installed the Phoenix web framework and all its dependencies correctly without errors. If you have not installed the Phoenix web framework please view the documentation here


To Create a Working Phoenix LiveView Instance please follow these instructions:


Rendering Dynamic Variables


defmodule AppWeb.PageLive do
   use AppWeb, :live_view  
   def mount(_params, _session, socket)  do
	 {:ok, assign(socket, greeting: "Hello World")}  
   end

   def render(assigns) do
	   ~H"""
		<%= assigns.greeting %>
	   """ 
   end
end


In the code example the string Hello World is assigned to the key greeting in the assign function. The render function exposes the content of greeting to the browser using this code: assigns.greeting .


As a short hand, in the render function you can replace the word assigns with an @ symbol.


Example


defmodule AppWeb.PageLive do
   use AppWeb, :live_view  
   def mount(_params, _session, socket)  do
	 {:ok, assign(socket, greeting: "Hello World")}  
   end

   def render(assigns) do
	   ~H"""
		<%= @greeting %>
	   """ 
   end
end