Using Underscore Result Template

Instead of using Underscore templates, you are encouraged to use HTML templates with custom components (see Creating Custom Components).

You can format your search results using Underscore templates (see Underscore.js).

In addition to the normal Underscore library, you can use Coveo Result Template Helpers to display field values in a consistent way.

You should only use Underscore templates when you need the added flexibility of JavaScript functions that the standard HTML Result Template does not offer, and when you cannot create custom components (see Creating Custom Components).

Underscore templates also support the Coveo JavaScript result template components (see Customizing Result Templates). You are encouraged to use those components whenever possible to simplify your result templates.

The markup for a simple lightweight Underscore template might look like this:

<script id='MyTemplate' type='text/underscore' class='result-template'>     // You specify that the template is an Underscore template by specifying its type.
    <div class="my-date"><%- dateTime(raw.sysdate) %></div>                 // Use a Coveo helper to format date and time, referencing the raw.sysdate property on each results.
    <div class='my-excerpt'><%= excerpt %></div>                            // Output the excerpt of the result in a div.

Precision on the delimiters

While reading the Underscore template engine documentation (see Underscore.js), you might notice that you can modify the delimiter (<% %>) to something else by changing the _.templateSettings object.

Changing the delimiters when using Underscore templates can cause issues with the Coveo JavaScript Search Framework, as they are used internally.

To alleviate this issue, the Coveo JavaScript Search Framework offers the {{ }} alternative delimiters, which work the same way as the default <% %> delimiters.

This can be useful when using the Coveo JavaScript Search Framework with certain other technologies, such as ASP.NEt or JavaServer Pages, which use the <% %> characters to let the server interpret expressions.

What’s Next?

When you have many result templates, remember to add conditions on them (see Understanding Which Result Template Loads for a Result).