How is `:page_title` updated?
Notes
You probably know that the :page_title assign is special in Phoenix – it is
the only dynamic assign in a layout.
I always wondered: how does it work? How do they make it special?
So, I did a bit of code spelunking. 🤿
You can do the same.
- Clone the
phoenix_live_viewrepo- Or, if you’re using LiveView in a project, just look in your project’s
depsdirectory
- Or, if you’re using LiveView in a project, just look in your project’s
- Search for
page_title.- Aside from tests and documentation, you should find it in
diff.ex
- Aside from tests and documentation, you should find it in
- There, you’ll see that
maybe_put_titlesets thepage_titleassigns to@title, which is just:t
Now we can navigate to the JS side:
- Open up
assets/js/phoenix_live_view - In
constants.js, you’ll see we assignttoTITLE TITLE, in turn, is used inrendered.jswhen weextractthe diff- And we call
Rendered.extractfromview.jswhen weapplyDiff. - In
view.js, when we get thetitle, we pass it toDOM.putTitle - Looking at
dom.js, you’ll see thatputTitlesets the title todocument.title.
So, as the docs state,
Assigning the
@page_titleupdates thedocument.titledirectly
Turns out that’s 100% accurate.
Hope you enjoyed code spelunking with me! 😁