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
- <!--#_
- window.PageSize = "30";
- _#-->
Item Template
- <!--#_ 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
- <!--#_
- ctx.PageSize = "30";
- _#-->
Item Template
- <!--#_ alert(ctx.PageSize);_#-->
Happy learning!