Get Category Name using JS

There might be a way to consistently do it across both topics and category pages, but I’ve gotten the category ID in two different ways… one for category pages:

<script type="text/discourse-plugin" version="0.8">
const container = Discourse.__container__;
const controller = container.lookup('controller:navigation/category');

api.onPageChange((url, title) => {
  console.log(controller.get("category.id"));
});
</script>

and a similar way for topic pages:

<script type="text/discourse-plugin" version="0.8">
const container = Discourse.__container__;
const controller = container.lookup('controller:topic');

api.onPageChange((url, title) => {
  console.log(controller.get("model.category_id"));
});
</script>

In the category page example you can alternatively use category.name or category.slug but with the topic model only the category_id is available so you’d have to do a little more work there to get the name. ID might be a better path anyway because it’s consistent even if the category name or slug changes.

9 Likes