How to Set Page Title Dynamically with Meteor, Iron Router and SEO
In my Meteor-based project MusitechHub, I recently had to figure out how to set page title dynamically for certain pages. I’m using Iron Router to implement routing in the application, which laid the premise for the solution.
I gathered from the #meteor channel on IRC that I could base my solution on Manuel Schoebel’s SEO package, which is able to set the current page title. Since I wasn’t able to figure out myself how to apply it, I continued by asking on Stack Overflow. Thanks to a helpful answer here, I figured out that I could use Iron Router’s onAfterAction hook to call SEO.set in order to set the title for a certain route/page:
@ProjectController = RouteController.extend({
[...]
onAfterAction: ->
data = @data()
if data?
title = "#{data.owner}/#{data.projectId}"
logger.debug("Setting title: #{title}")
SEO.set({
title: "MusitechHub - #{title}"
})
else
logger.debug("@data is not defined")
})
I was a bit worried that the title would stick even after navigating away from one of these pages, but magically, it seems that the title is reset to the default when navigating to another route. Great.