Sharing Variable Values Between Search Control And Display Templates

Recently, I came across a scenario where I needed to set the variable in control template and the value of the variable should be accessible in item template and vice versa.

I was showing some data in item templates using third-party pagination for displaying the search result. I needed the value of pagination size which is available in control template.

I tried with a normal JavaScript variable but due to the scoping in display template, it was not available for me inside the item template.

Solution 1

We can use Windows.variable which is nothing but global variable creation on the scope of the Windows object and, hence, will be accessible throughout the scope of the Windows object.

Control Template

  1. <!--#_  
  2.     window.PageSize = "30";  
  3. _#--> 

Item Template

  1. <!--#_    alert(window.PageSize);_#-->  

Solution 2

Another better alternative is to use the built-in ctx object which is already shared between the control and item display template.

Control Template

  1. <!--#_  
  2.     ctx.PageSize = "30";  
  3. _#-->  

Item Template

  1. <!--#_    alert(ctx.PageSize);_#-->  

Happy learning!