Running Client Script in a Display Template After Rendering is Complete in SharePoint 2013

My friend Bryan asked me a good question the other day about how to create a display template that would do its rendering thing, but then run his own javascript function afterwards.  After doing some snooping around, one of my other buddies Jesus was good enough to share the magic mystery meat to this problem.  To invoke your own function after the template renders, you need to add this the javascript section of your display template – by that I mean in the javascript you add below the first <div> tag in the page with any other js you will use for rendering your template.  In that javascript you need to add a callout like this:

<!–#_
AddPostRenderCallback(ctx, function()
{             
     //code to execute
});
_#–>

 

Now, this alone was not enough to solve Bryan’s problem.  He needed to obtain a ClientContext for some additional CSOM calls he wanted to make.  As it turns out, just trying to create it in this delegate doesn’t work because we don’t load all of the scripts in the search results page.  So, in order to get the current context you can call Srch.ScriptApplicationManager.get_clientRuntimeContext().  If there are other scripts that you need to load in your display templates you can use the EnsureScriptFunc method, like this:  EnsureScriptFunc(“sp.js”, “SP.ClientContext”, function () { //callback  }); .

One thought on “Running Client Script in a Display Template After Rendering is Complete in SharePoint 2013

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s