How is `:page_title` updated?

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
  • Search for page_title.
    • Aside from tests and documentation, you should find it in diff.ex
  • There, you’ll see that maybe_put_title sets the page_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 assign t to TITLE
  • TITLE, in turn, is used in rendered.js when we extract the diff
  • And we call Rendered.extract from view.js when we applyDiff.
  • In view.js, when we get the title, we pass it to DOM.putTitle
  • Looking at dom.js, you’ll see that putTitle sets the title to document.title.

So, as the docs state,

Assigning the @page_title updates the document.title directly

Turns out that’s 100% accurate.

Hope you enjoyed code spelunking with me! 😁

Want the latest Elixir Streams in your inbox?

    No spam. Unsubscribe any time.