Creating And Calling Custom JavaScript Function In Search Display Template

Recently, I came across a requirement where I needed to create a custom JavaScript function which will change the date formatting on the provided string date parameter.

I tried creating normal JavaScript function in display template and tried calling it from another part of the template but the function was undefined and not found inside the display template. I got a little bit confused as I have created the JavaScript function in the same display template but still not able to find it there while calling. We can have a couple of ways to resolve the issue.

Solution 1

After some Googling, I found the cause of the issue and the solution as well. The possible reason is, the scoping of the display template not allowing us to consider external JavaScript function as a part of the scope to call inside display template.

The solution is to create a new function on Windows scope and the call in the desired place inside display template.

  1. window.MyTestFunction = function(myParam)  
  2. {  
  3.    // your own logic to work on the param 'myParam'                            
  4. }  

Calling the function,

  1. <a style="cursor:pointer" onclick='window.MyTestFunction(3)'>Call My custom JS function</a>  

Solution 2

  1. Create a JavaScript file (MySampleJS.js) in the Display Templates/Search folder.
  2. Add the custom JS function into the MySampleJS.js file.
  3. Add the following code into the <body> tag below, to include the JS file in display template.
    1. <script>  
    2.    $includeScript(this.url, "~sitecollection/_catalogs/masterpage/Display Templates/Search/ MySampleJS.js");  
    3. </script>  
Ebook Download
View all
Learn
View all