Introduction
Your first Live View
Read time: 2 minutes
#One step at a time
The Phoenix framework brings with it several tools configured so you don't have to worry: sending emails, real-time presence system, clustering, etc. For the sake of simplicity we will learn those things as we go so feel free to ignore all those files generated by the framework and let's focus on creating your first LiveView.
#The most basic LiveView
For convenience's sake we will create a folder called live inside lib/myapp_web so we can store our LiveViews. The command below should do the trick:
mkdir lib/myapp_web/live
Then let's create our first LiveView. With your favorite editor, create a file called page_live.ex inside lib/myapp_web/live:
# contents of page_live.ex
defmodule MyappWeb.PageLive do
use MyappWeb, :live_view
def render(assigns) do
~H"""
Hello World
"""
end
end
Now we need to tell Phoenix where this LiveView should be rendered at. Open lib/myapp_web/router.ex and look for a section just like this:
scope "/", MyappWeb do
pipe_through :browser
get "/", PageController, :home
end
Replace get "/", PageController, :home with live "/", PageLive, :home and your hello world will be available at http://localhost:4000. Your router should look like this:
scope "/", MyappWeb do
pipe_through :browser
live "/", PageLive, :home
end
#What did I just write?
We created a module MyappWeb.PageLive to be our first LiveView and we told Phoenix to render it at the root path /. As you can see at the very top we used use MyappWeb, :live_view to make it a LiveView by installing all the necessary behind the scenes code you don't need to worry about.
You may have noticed, but there's a lot of MyappWeb going in there. This is because we are using the MyappWeb namespace for our LiveView. In Phoenix projects you will often see that projects called Project have a matching ProjectWeb module to encapsulate all the web-related code.
#Try it out
Try putting some HTML in your render/1 function.
#Success!
Now that you have LiveView Playground in your hands, in the next steps we will understand what each piece of this code represents.
Feedback
Got any feedback about this page? Let us know!