My Title My Title My Title

How to update the title through Hotwire?

77 Views Asked by At

how do people update the title with hotwire? are people still using this hack?

<head>
  <title id="page-title">My Title</title>
</head>
<body>
  <turbo-frame data-turbo-action="advance" ...>
  
  <turbo-frame>
</body>
<turbo-frame ...>
  <turbo-stream action="update" target="page-title">
    <template>New Title</template>
  </turbo-stream>

  Content...
<turbo-frame>
1

There are 1 best solutions below

0
Alex On

Here is another idea:

// app/javascript/application.js

document.addEventListener("turbo:before-frame-render", (event) => {
  const title = event.detail.newFrame.getAttribute("title");
  if (title) {
    document.title = title;
  };
});
<%= turbo_frame_tag :my_frame, data: {turbo_frame: :advance} do %>
  content
<% end %>

and then set title attribute on your other frame:

<%= turbo_frame_tag :my_frame, title: "new title" do %>
  new content
<% end %>

If you render your application layout instead of the default frame layout the title will be updated automatically:

render layout: "application"

One other way is to render your entire head tag, which will cause it to be merged with the current page head tag:

<%= turbo_frame_tag :my_frame do %>
  <% content_for :head do %>
    <%= render "layouts/head" %> # you'll have to extract it into a partial
  <% end %>

  content
<% end %>