Sharepoint - SP.ClientContext is always "undefined" in JSLink functions
SharePoint 2013 CSR OnPreRender
handler could used for initialization of ClientContext
since OnPreRender
is called before the actual View/Fields rendering
Example:
(function () {
function OnPreRenderDocItemTemplate(renderCtx) {
SP.SOD.executeOrDelayUntilScriptLoaded(loadContext, 'sp.js');
function loadContext() {
var context = SP.ClientContext.get_current();
var web = context.get_web();
}
}
function RegisterDocViewTemplate() {
var viewContext = {};
viewContext.Templates = {};
viewContext.Templates.OnPreRender = OnPreRenderDocItemTemplate;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(viewContext);
}
ExecuteOrDelayUntilScriptLoaded(RegisterDocViewTemplate, 'clienttemplates.js');
})();
I worked around this problem by having the custom render function return just a placeholder HTML element, and using a $(window).load handler to later populate the element with content obtained through JSOM calls.
By the time the handler executes, the necessary JavaScript libraries have already been loaded, and SP.ClientContext is also available.
I experienced the same issue using JSLink in O365 Sharepoint Online. My solution was to call my function requiring SP.ClientContext as follows:
//Perform SP.ClientContext tasks after sp.js is loaded
window.onload = function() { SP.SOD.executeFunc('sp.js','SP.ClientContext', someFunction()); };