Gravatar for acastro@bluetubeinc.com

Question by acastro, Jul 31, 2014 4:35 PM

Register new Template Helper

I'm trying to register a new template helper but I'm not having much luck. At what point do I register my template helper?

I noticed in the CoveoJsSearch.js you register the template helpers using

Ui.TemplateHelpers.registerTemplateHelper('javascriptEncode', function (value) { return Coveo.Utils.exists(value) ? Coveo.StringUtils.javascriptEncode(value) : undefined; });

Do I have to go in and register it with the rest of the helpers in the CoveojsSearch or can I manually add them before/after init.

2 Replies
Gravatar for olamothe@coveo.com

Answer by olamothe, Jul 31, 2014 4:59 PM

It depends on the template engine you are using but i'm assuming you are using underscore.

In that case, it's as simple as adding your function/helpers directly to the main underscore object that is used each time you are rendering a template.

There are many way to do this, but an easy one would be to have something that roughly looks like this :


function loadMyTemplateHelpers(underscoreObject){
 _.extend(underscoreObject, allMyTemplateHelpers);
}
var allMyTemplateHelpers = {
   firstHelper : function(){...},
   secondHelper : function(){...},
   etc..
}
<script id="MyTemplate" class="result-template" type="text/x-underscore-template" > 
<% loadMyTemplateHelpers(obj) %> //obj represent the main underscore object, with the result and the coveo helpers. This function will extend it's property <% firstHelper() %> //Should be accessible now <script>

If you are using another template engine, then it depends. The documentation for js render or Handlebars should help you figure it out.

Hope I was able to help !

Gravatar for acastro@bluetubeinc.com

Comment by acastro, Jul 31, 2014 6:05 PM

This worked perfectly. Thank you so much. I'm new to underscore so I was having trouble understanding some of the concepts.

Gravatar for olamothe@coveo.com

Comment by olamothe, Jul 31, 2014 6:18 PM

Hey, no problem. Don't forget to accept the answers, this will help other people with the same problem.

Also, what Martin was saying is also true : You don't absolutely need helpers since you can execute any javascript code inside an underscore template anyway. You could call you functions directly with <% allMyTemplateHelpers.firstHelper() %> without adding them to the global/main underscore object, for example.

Gravatar for mlaporte@coveo.com

Answer by Martin Laporte, Jul 31, 2014 4:46 PM

Are you using Underscore templates? Because you don't really need template helpers with those, since the code you put there has access to the JavaScript global scope. E.g. you can call functions like helpers.

But yes, although this API is technically undocumented you can register custom helpers that way. You can do it before init. It also works after, as long as you do it before any result template gets rendered.

Ask a question