Share-n-dipity

SharePoint serendipity is the effect by which one accidentally discovers something fortunate, especially while looking for something else entirely. In this case, it is the occassional musings, observations, and Ouija board readings about the phabulously

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

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

  • Comments 2
  • Likes

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  }); .

Comments
  • Seems like get_clientRuntimeContext() doesn't have get_web() method. I'd need to look for the user's PictureUrl from the hidden user information list so I could display blog author thumbnail picture when showing latest blog posts in Content Search WP.

    Any tips on how would I start solving that task?

  • Thanks for posting this.  I do a lot of DOM manipulation with jQuery and I was afraid that the asynchronous approach MS took for templates in 2013 was going to force me to rethink everything.

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment