Trouble with renderInOutlet

AI-generated summary

The discussion Trouble with renderInOutlet revolves around pfaffman’s issue with rendering a template on the home page using renderInOutlet. pfaffman (#1) is trying to render “HELLO WORLD” on the home page, but it’s not working, despite the code firing and logging “THIS IS THE HOMEPAGE” to the console.

merefield (#2) suggests that the outlets might not be rendered yet, causing the issue. pfaffman (#3) confirms this and finds that moving the renderInOutlet call outside of onPageChange makes it work. However, pfaffman wants to render the template only on the home page.

merefield (#4) recommends using a component with the router service and a getter to achieve this. pfaffman (#5) expresses gratitude and eventually (#7) confirms that the solution works, with the text now rendering on the home page and not on other pages.

I must be doing something very stupid, but I’m incapable of seeing it. I’m hoping that posting here will make me see it so I can delete this before anyone else knows how stupid I am.

“HELLO WORLD” should be rendering on the home page. I see “THIS IS THE HOMEPAGE” in the console. I know it’s firing. But it’s not there.

Then I tried adding “Extra item” because I didn’t have any other ideas. It’s not rendering either.

I did get errors before I renamed the file to .gjs, so that’s further evidence that it’s paying attention to the file and it’s making something happen.

import { apiInitializer } from "discourse/lib/api";

export default apiInitializer("1.8.0", (api) => {
  // see if we're on the home page
  api.onPageChange(() => {
    const router = api.container.lookup("service:router");
    const url = router?.currentURL;
    const isHomePage = url === "/";
    api.renderInOutlet("top-notices", <template>Extra item</template>);
    if (isHomePage) {
      console.log("THIS IS THE HOMEPAGE");
      api.renderInOutlet("after-header", <template>HELLO WORLD</template>);
    }
  });
});

Is it possible the outlets aren’t yet rendered so there is no outlet to attach to?

onPageChange is fired on a route change …

That sounds like the kind of stupid thing I’m talking about!!

I want this to happen only the home page.

But yes! If I move one of those render thingies out of the onPageChange, it renders.

So how do I make this happen only if the URL is /?

Maybe I make a real component and add a shouldRender() call?

you should add the router service (within a Component) and set up a getter.

Thanks a zillion! I mostly know what all of those words mean!

Well I’m hoping this helps! Please confirm once it’s all fired up!

Oh, baby! I really did know what a service was! I really did know what a getter was! Now my text is rendering on the home page and not on another page (and presumably all of the rest of them!).