How to create a Handlebar helper function

Hi,

I want to create a new helper function which can be across the application. I am not sure how to create a helper function.

Likewise, I tried myself to create a helper function, but it is not working.

Please find my code.

I am referring to this helper function in .hbr file. Please find the attached screenshot.

Please suggest me.

Thanks
Kumar

Can anyone please help me on this?

Did you see Developer’s guide to Discourse Themes?

What I usually do is look at existing themes or plugins for examples.

EDIT: But if you’re lucky @Johani will provide a really thoughtful and helpful answer. And you’re lucky!

3 Likes

Your code should work, but you’re using your helper

{{sample}}

in the template without passing it any arguments. Even if you’re testing to see if things work, pass it a test string like

{{sample "some string"}}

You need to do that because you’re using the helper in a raw hbr template. For testing purposes, the helper should work even if you don’t pass it anything in regular hbs templates.

If you’re creating a block-helper, then it needs to have # and you need to close it like so.

{{#sample}}

{{/sample}}

Adding ~ to your helper optionally trims whitespace between any HTML tags it returns. So

{{~#sample}}

{{/sample}}
6 Likes

Thank you so much for your reply. It is working fine now,

1 Like

Hi,

Thank you for your reply. You are helping me a lot.

Yes, I have already gone through the documentation, existing themes and few examples, and created this sample project. But I am not sure about how to call the helper function in handlebar file. I tried it in multiple ways, and it was not working. That’s why, I posted here.

Thanks
Kumar

1 Like

Your question helped me too, thanks to @Johani! I’m going to look at refactoring some of my code as a result.

2 Likes