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.
- window.MyTestFunction = function(myParam)
- {
-
- }
Calling the function,
- <a style="cursor:pointer" onclick='window.MyTestFunction(3)'>Call My custom JS function</a>
Solution 2
- Create a JavaScript file (MySampleJS.js) in the Display Templates/Search folder.
- Add the custom JS function into the MySampleJS.js file.
- Add the following code into the <body> tag below, to include the JS file in display template.
- <script>
- $includeScript(this.url, "~sitecollection/_catalogs/masterpage/Display Templates/Search/ MySampleJS.js");
- </script>