I have something like this in my JS tab of my theme:
import { apiInitializer } from "discourse/lib/api";
export default apiInitializer("0.11.1", (api) => {
api.renderInOutlet("above-main-container",
<template>
<div>
html stuff
</div>
</template>
);
});
I copy pasted that, it works (just an example)
How do I make this render only on the home page or only on the categories page
sorry if this is not a good question
It’s a good question, don’t worry about it! This will work:
import Component from "@glimmer/component";
import { service } from "@ember/service";
import { apiInitializer } from "discourse/lib/api";
import { defaultHomepage } from "discourse/lib/utilities";
class HomepageOnly extends Component {
@service router;
get shouldShow() {
return this.router.currentRouteName === `discovery.${defaultHomepage()}`;
}
<template>
{{#if this.shouldShow}}
<div>
html stuff
</div>
{{/if}}
</template>
}
export default apiInitializer((api) => {
api.renderInOutlet("above-main-container", HomepageOnly);
});
This creates a new component, which uses the router service and defaultHomepage utility to check if you’re on the homepage. Then the component is rendered in the outlet.
There’s a little more here: Add custom content that only appears on your homepage
Thank you Kris, that works perfectly. Thanks for the link as well, trying to learn.
I have a follow on question for anybody
My little chunk of injected html makes a nice banner on my home page and it loads and works. I placed the following in the tab of my theme:
document.addEventListener('DOMContentLoaded', loadMyWidget);
It works but when I navigate away to another page then return to the home page my widget does not load again. I tried adding:
window.addEventListener('focus', loadMyWidget);
But that didn’t help, can anybody help me, should I start a new topic to ask this?
EDIT:
I think I figured it out
I added this to my export default apiInitializer((api) => {
api.onPageChange(() => {
const myWidget = document.querySelector("#widget-container");
if (myWidget) {
window.loadMyWidget();
}
});
and it reloads my widget on returning to the home page