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_view
repo- Or, if you’re using LiveView in a project, just look in your project’s
deps
directory
- 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_title
sets thepage_title
assigns 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 assignt
toTITLE
TITLE
, in turn, is used inrendered.js
when weextract
the diff- And we call
Rendered.extract
fromview.js
when weapplyDiff
. - In
view.js
, when we get thetitle
, we pass it toDOM.putTitle
- Looking at
dom.js
, you’ll see thatputTitle
sets the title todocument.title
.
So, as the docs state,
Assigning the
@page_title
updates thedocument.title
directly
Turns out that’s 100% accurate.
Hope you enjoyed code spelunking with me! 😁