Can JavaScript get the slug, tags, etc?

  • What’s your URL?
    https://cathy.sarisky.link (although its probably not relevant here)
  • What version of Ghost are you using? If it’s not the latest, please update Ghost first before opening your topic
    Self-hosted Ghost (Ubuntu v-server), 5.10.something.

(OK, I’m not using the rest of the template because it doesn’t fit my question.)

I’m curious if there’s a way for JavaScript (either in the assets folder of a custom theme or from code injection) to access the properties of a post, such as the slug, tags, and so on. I know how to get tags and slugs into the .hbs file, and then I can do some conditional rendering based on them, but I’ve got a use case where I’d like to have some JavaScript change behavior depending on tags and/or slug, and I’m not sure how to pull that one off. Can someone give me a pointer at an example or some documentation?

(Specific use case: I want to make an API call to an external data source that filters based on the tag/slug for the post being rendered.)

There are a few ways of doing this.

The approach I would use is to modify your theme to include a data attribute somewhere in the post template.

<article class="post-content" data-slug="{{slug}}">
...
</article>

{{! output }}
<article class="post-content" data-slug="baseball">

Then, you can access the slug with JavaScript:

const el = document.querySelector('[data-slug]');

// If the element doesn't exist, abort
if (!el) return;

const {slug} = el.dataset;
// console.log(slug) -> "baseball"

// Do your API call
1 Like

@RyanF, thank you! I’ll give that a go, but that looks like exactly what I need!

1 Like