How to register a helper in Discourse?

I’m trying to figure out the best way to register a handlebars helper for my Discourse plugin.

I have an ajax call in my initializer that determines whether the currentUser is part of a particular group. If they are, then they get an extra nav item.

I wanted to do something like this in my hbs file for the nav:

{{#if customHelper}}
//show nav item
{{/if}}

My other theories on how to do this:

  1. Keep the logic in the initializer and use jquery to append the item to the nav.
  2. Create a component for the nav item to only be displayed given the aforementioned logic.

So do you think registering a helper is the best to go, if so how? Or are one of my other approached better.

Thanks for any help or advise!

What would customHelper do? Can’t you just do something like this instead?

in your initializer

export default {
  initialize(container) {
    const user = container.lookup('current-user:main');
    Discourse.ajax("/some-url").then(result => user.set("isPartOfParticularGroup", true));
  }
}

and in your .hbs file

{{#if currentUser.isPartOfParticularGroup}}
   // your stuff
{{/if}

Wow so simple and works perfectly!

很抱歉重新提起这个话题,但它与我的问题非常契合。

是否可以在不创建插件的情况下注册一个辅助函数?比如从主题 HTML 的 head 或 body 部分的脚本中注册?

提前感谢!

通常你会使用一个 主题组件 来完成,没错。