AddPostRenderCallback in ItemTemplate is not getting called in Sharepoint Online
-
11-12-2020 - |
質問
Hi I have an item template. In which below is the code for the AddPostRenderCallback.
AddPostRenderCallback(context, function () {
alert("Inside Addpostrendercallback");
});
This piece of code does not get executed. I tried using the developer tools debuger, still the debug point on alert is not hit. It simply doesnt go inside the function.
When i step on to
in the debugger on the AddPostRenderCallback
function it goes to clienttemplate.js and debugger is on AddRenderCallback(b,"OnPostRender",a,false) undefined
. I think false attribute is causing it to not fire. Any suggestions?
Full code
Test Events Item
<!--[if gte mso 9]><xml>
<mso:CustomDocumentProperties>
<mso:TemplateHidden msdt:dt="string">0</mso:TemplateHidden>
<mso:MasterPageDescription msdt:dt="string"></mso:MasterPageDescription>
<mso:ContentTypeId msdt:dt="string">0x0101002039C03B61C64EC4A04F5361F385106603</mso:ContentTypeId>
<mso:TargetControlType msdt:dt="string">;#SearchResults;#</mso:TargetControlType>
<mso:HtmlDesignAssociated msdt:dt="string">1</mso:HtmlDesignAssociated>
<mso:ManagedPropertyMapping msdt:dt="string">'Title':'Title','RefinableString103':'RefinableString103','RefinableString102':'RefinableString102','RefinableDate04':'RefinableDate04','RefinableString100':'RefinableString100','RefinableDate00':'RefinableDate00','Path':'Path','Description':'Description','EditorOWSUSER':'EditorOWSUSER','LastModifiedTime':'LastModifiedTime','CollapsingStatus':'CollapsingStatus','DocId':'DocId','HitHighlightedSummary':'HitHighlightedSummary','HitHighlightedProperties':'HitHighlightedProperties','FileExtension':'FileExtension','ViewsLifeTime':'ViewsLifeTime','ParentLink':'ParentLink','FileType':'FileType','IsContainer':'IsContainer','SecondaryFileExtension':'SecondaryFileExtension','DisplayAuthor':'DisplayAuthor','PictureHeight':'PictureHeight','PictureWidth':'PictureWidth','ImageDateCreated':'ImageDateCreated','PictureThumbnailURL':'PictureThumbnailURL','PictureURL':'PictureURL','AgnBlurbOWSTEXT':'AgnBlurbOWSTEXT','AgnArticleTypeOWSCHCS':'AgnArticleTypeOWSCHCS','ArticleStartDateOWSDATE':'ArticleStartDateOWSDATE','PublishingImage':'PublishingImage'</mso:ManagedPropertyMapping>
<mso:HtmlDesignStatusAndPreview msdt:dt="string">https:/dev.sharepoint.com/sites/Dev/_catalogs/masterpage/Display%20Templates/Search/It.html, Conversion successful.</mso:HtmlDesignStatusAndPreview>
<mso:HtmlDesignConversionSucceeded msdt:dt="string">True</mso:HtmlDesignConversionSucceeded>
<mso:CrawlerXSLFile msdt:dt="string"></mso:CrawlerXSLFile>
<mso:HtmlDesignPreviewUrl msdt:dt="string"></mso:HtmlDesignPreviewUrl>
</mso:CustomDocumentProperties>
</xml><![endif]-->
</head>
<body>
<script>
Type.registerNamespace('search.eventdate');
search.eventdate = function () {
var itemInfo = {};
var init = function (context, elmId) {
var eStartDate = $getItemValue(context, "RefinableDate00");
var eEndDate = $getItemValue(context, "RefinableDate04");
var Location = $getItemValue(context, "RefinableString100");
// Store item info
itemInfo[elmId] = {};
itemInfo[elmId]["EventStartDate"] = eStartDate;
itemInfo[elmId]["EventEndDate"] = eEndDate;
itemInfo[elmId]["Location"] = Location;
itemInfo[elmId]["EventDivId"] = context.ClientControl.get_nextUniqueId();
// Add an on post render callback, this will be excuted when all the results are rendered
context.OnPostRender = function () {
alert('hello world');
get(elmId);
};
//AddPostRenderCallback(context, function () {
// $(".content-news-item-date2").css("color", "red");
// get(elmId);
//});
},
get = function (elmId) {
console.log("In get fn for " + elmId);
},
// Set the userGUID as class name to the SPAN element
setClass = function (elmId, userGuid) {
},
// Write the document FollowStatus to all elements with the same GUID
render = function (elmId, userGuid) {
},
quickRender = function (elmId, userGuid) {
};
return {
init: init
};
}();
</script>
<div>
<!--#_
var locationOffset = "";
var offsetTime = "";
function getUser(currentItemObject) {
var userid = _spPageContextInfo.userId;
console.log("getting userid method: " + userid);
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
console.log("getting requestUri method: " + requestUri);
var requestHeaders = { "accept": "application/json;odata=verbose" };
$.ajax({
async: false,
url: requestUri,
contentType: "application/json;odata=verbose",
headers: requestHeaders,
success: onSuccess,
error: onError
}); function onSuccess(data, request) {
var loginName = data.d.LoginName;
getUserProfileProperty(loginName,"SPS-Location",currentItemObject);
} function onError(error) {
console.log("Error on retrieving current user.");
}
}
function getUserProfileProperty(loginName, property, currentItemObject) {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/sp.userprofiles.peoplemanager/getuserprofilepropertyfor(accountName='" + escape(loginName) + "', propertyname='" + property + "')";
var requestHeaders = { "accept": "application/json;odata=verbose" };
$.ajax({
async: false,
url: requestUri,
contentType: "application/json;odata=verbose",
headers: requestHeaders,
success: onSuccess,
error: onError
}); function onSuccess(data, request) {
var fetchedProperty = data.d.GetUserProfilePropertyFor;
var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
if (siteUrl != null && siteUrl != "") {
if (siteUrl.indexOf("/sites/") != -1) { siteUrl = siteUrl.split("sites"); siteUrl = siteUrl[0];}
}
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('Locations');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='AgnLocation'/>" + "<Value Type='TaxonomyFieldType'>" + fetchedProperty + "</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>");
var collListItem = oList.getItems(camlQuery);
var locationURL = "";
var isActive = "";
clientContext.load(collListItem, 'Include(AgnOffset,AgnLocation)');
clientContext.executeQueryAsync(function () {
console.log("Inside the async function");
if (collListItem.get_count() == 0) {
}
else {
var enumerator = collListItem.getEnumerator();
while (enumerator.moveNext()) {
var item = enumerator.get_current();
locationOffset = item.get_item('AgnOffset');
locationOffset = locationOffset *0.01;
var eventStartDate = currentItemObject.RefinableDate00;
var targetTime = new Date(eventStartDate);
//get the timezone offset from local time in minutes
var tzDifference = locationOffset * 60;
//convert the offset to milliseconds, add to targetTime, and make a new Date
offsetTime = new Date(targetTime.getTime() + tzDifference * 60 * 1000);
//alert(eventStartDate + offsetTime);
}
}
},
function (s, a) {
console.error(a.get_message());
});
}function onError(error) {
alert("Error on retrieving current user location:" + error.responseText);
}
}
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
if(!$isNull(ctx.CurrentItem) && !$isNull(ctx.ClientControl)){
var id = ctx.ClientControl.get_nextUniqueId();
var itemId = id + Srch.U.Ids.item;
var eventStartDate = $getItemValue(ctx, "RefinableDate00");
var s = formatAMPM(new Date(eventStartDate.inputValue));
var eventEndDate = $getItemValue(ctx, "RefinableDate04");
var Location = $getItemValue(ctx,"RefinableString100");
if(Location != "") {} else {Location=Location; }
getUser(ctx.CurrentItem);
var startYear = new Date(eventStartDate.inputValue).format('yyyy');
var startDate = new Date(eventStartDate.inputValue).format('dd');
var startMonth = new Date(eventStartDate.inputValue).format('MMM');
var endYear ="";
var endDate = "";
var endMonth = "";
var endPMAM = "";
if(eventEndDate!="")
{
endYear = new Date(eventEndDate.inputValue).format('yyyy');
endDate = new Date(eventEndDate.inputValue).format('dd');
endMonth = new Date(eventEndDate.inputValue).format('MMM');
endPMAM = formatAMPM(new Date(eventEndDate.inputValue));
}
else
{
endYear = "endYear";
endDate = "endDate";
endMonth = "endMonth";
endPMAM = "EndAMPM";
}
var EventDivId = id + "EventContainer";
search.eventdate.init(ctx, EventDivId);
_#-->
<div class="content-news-item" >
<div class="content-news-item-icon">
<div class="content-news-item-icon-in">
<div class="content-news-icon">
<!-- _#= ctx.CurrentItem.PublishingImage =#_
<img src="_#= ctx.CurrentItem.PublishingImage =#_" width="570" height="270" alt="_#= $htmlEncode(ctx.CurrentItem.Title) =#_">-->
</div>
</div>
</div>
<div class="content-news-item-info">
<div class="content-news-item-date">_#= startYear + " "+ startMonth + " " + startDate + " To " + endYear + endMonth + " " + endDate =#_</div>
<div class="content-news-item-date">_#= s + " - " + endPMAM =#_</div>
<div class="content-news-item-date2">_#= Location =#_</div>
<div class="content-news-item-date2">_#= offsetTime + " offset time" =#_</div>
<div id="_#= $htmlEncode(EventDivId) =#_">
<div class="EventDateUserClass">
</div>
</div>
<div class="content-news-item-date2">
<a href='_#= _spPageContextInfo.webAbsoluteUrl + "/_vti_bin/owssvr.dll?CS=109&Cmd=Display&List=" + $htmlEncode(ctx.CurrentItem.RefinableString103) + "&CacheControl=1&ID=" + $htmlEncode(ctx.CurrentItem.RefinableString102) + "&Using=event.ics" =#_'>Add to OutLook</a>
</div>
<div class="content-news-item-title"><a href="_#= ctx.CurrentItem.Path =#_" class="slide-title">_#= $htmlEncode(ctx.CurrentItem.Title) =#_</a></div>
</div>
</div>
<!--#_
}
_#-->
</div>
</body>
</html>
Any suggestions
解決
Try to register your custom method as follows in the Script Block of your display template:
Srch.U.registerRenderTemplateByName("mycustomfunction", MyCustomFunction);
function MyCustomFunction(ctx) {
....
}
And then call your function from the html part(respectively from the javascript block in your html):
Srch.U.getRenderTemplateCollection().mycustomfunction(ctx)
In the custom function you can call your module/your function search.eventdate.init(ctx, EventDivId);
他のヒント
try it as below. Make sure its inside <!--#_ _#-->
block
<!--#_
AddPostRenderCallback(ctx, function(){
alert('Hi');
CallAnotherMethod("Hi");
});
CallAnotherMethod(str)
{
alert(str);
}
_#-->
Another way to reference it is as below:
ctx.OnPostRender = function() {
alert('hello world');
};
Edit Based on comments check the below updated display template code:
<!--[if gte mso 9]><xml>
<mso:CustomDocumentProperties>
<mso:TemplateHidden msdt:dt="string">0</mso:TemplateHidden>
<mso:MasterPageDescription msdt:dt="string"></mso:MasterPageDescription>
<mso:ContentTypeId msdt:dt="string">0x0101002039C03B61C64EC4A04F5361F385106603</mso:ContentTypeId>
<mso:TargetControlType msdt:dt="string">;#SearchResults;#</mso:TargetControlType>
<mso:HtmlDesignAssociated msdt:dt="string">1</mso:HtmlDesignAssociated>
<mso:ManagedPropertyMapping msdt:dt="string">'Title':'Title','RefinableString103':'RefinableString103','RefinableString102':'RefinableString102','RefinableDate04':'RefinableDate04','RefinableString100':'RefinableString100','RefinableDate00':'RefinableDate00','Path':'Path','Description':'Description','EditorOWSUSER':'EditorOWSUSER','LastModifiedTime':'LastModifiedTime','CollapsingStatus':'CollapsingStatus','DocId':'DocId','HitHighlightedSummary':'HitHighlightedSummary','HitHighlightedProperties':'HitHighlightedProperties','FileExtension':'FileExtension','ViewsLifeTime':'ViewsLifeTime','ParentLink':'ParentLink','FileType':'FileType','IsContainer':'IsContainer','SecondaryFileExtension':'SecondaryFileExtension','DisplayAuthor':'DisplayAuthor','PictureHeight':'PictureHeight','PictureWidth':'PictureWidth','ImageDateCreated':'ImageDateCreated','PictureThumbnailURL':'PictureThumbnailURL','PictureURL':'PictureURL','AgnBlurbOWSTEXT':'AgnBlurbOWSTEXT','AgnArticleTypeOWSCHCS':'AgnArticleTypeOWSCHCS','ArticleStartDateOWSDATE':'ArticleStartDateOWSDATE','PublishingImage':'PublishingImage'</mso:ManagedPropertyMapping>
<mso:HtmlDesignStatusAndPreview msdt:dt="string">https:/dev.sharepoint.com/sites/Dev/_catalogs/masterpage/Display%20Templates/Search/It.html, Conversion successful.</mso:HtmlDesignStatusAndPreview>
<mso:HtmlDesignConversionSucceeded msdt:dt="string">True</mso:HtmlDesignConversionSucceeded>
<mso:CrawlerXSLFile msdt:dt="string"></mso:CrawlerXSLFile>
<mso:HtmlDesignPreviewUrl msdt:dt="string"></mso:HtmlDesignPreviewUrl>
</mso:CustomDocumentProperties>
</xml><![endif]-->
</head>
<body>
<script>
Type.registerNamespace('search.eventdate');
search.eventdate = function () {
var itemInfo = {};
var init = function (context, elmId) {
var eStartDate = $getItemValue(context, "RefinableDate00");
var eEndDate = $getItemValue(context, "RefinableDate04");
var Location = $getItemValue(context, "RefinableString100");
// Store item info
itemInfo[elmId] = {};
itemInfo[elmId]["EventStartDate"] = eStartDate;
itemInfo[elmId]["EventEndDate"] = eEndDate;
itemInfo[elmId]["Location"] = Location;
itemInfo[elmId]["EventDivId"] = context.ClientControl.get_nextUniqueId();
// Add an on post render callback, this will be excuted when all the results are rendered
},
get = function (elmId) {
console.log("In get fn for " + elmId);
},
// Set the userGUID as class name to the SPAN element
setClass = function (elmId, userGuid) {
},
// Write the document FollowStatus to all elements with the same GUID
render = function (elmId, userGuid) {
},
quickRender = function (elmId, userGuid) {
};
return {
init: init
};
}();
</script>
<div>
<!--#_
var locationOffset = "";
var offsetTime = "";
function getUser(currentItemObject) {
var userid = _spPageContextInfo.userId;
console.log("getting userid method: " + userid);
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
console.log("getting requestUri method: " + requestUri);
var requestHeaders = { "accept": "application/json;odata=verbose" };
$.ajax({
async: false,
url: requestUri,
contentType: "application/json;odata=verbose",
headers: requestHeaders,
success: onSuccess,
error: onError
}); function onSuccess(data, request) {
var loginName = data.d.LoginName;
getUserProfileProperty(loginName,"SPS-Location",currentItemObject);
} function onError(error) {
console.log("Error on retrieving current user.");
}
}
function getUserProfileProperty(loginName, property, currentItemObject) {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/sp.userprofiles.peoplemanager/getuserprofilepropertyfor(accountName='" + escape(loginName) + "', propertyname='" + property + "')";
var requestHeaders = { "accept": "application/json;odata=verbose" };
$.ajax({
async: false,
url: requestUri,
contentType: "application/json;odata=verbose",
headers: requestHeaders,
success: onSuccess,
error: onError
}); function onSuccess(data, request) {
var fetchedProperty = data.d.GetUserProfilePropertyFor;
var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
if (siteUrl != null && siteUrl != "") {
if (siteUrl.indexOf("/sites/") != -1) { siteUrl = siteUrl.split("sites"); siteUrl = siteUrl[0];}
}
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('Locations');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='AgnLocation'/>" + "<Value Type='TaxonomyFieldType'>" + fetchedProperty + "</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>");
var collListItem = oList.getItems(camlQuery);
var locationURL = "";
var isActive = "";
clientContext.load(collListItem, 'Include(AgnOffset,AgnLocation)');
clientContext.executeQueryAsync(function () {
console.log("Inside the async function");
if (collListItem.get_count() == 0) {
}
else {
var enumerator = collListItem.getEnumerator();
while (enumerator.moveNext()) {
var item = enumerator.get_current();
locationOffset = item.get_item('AgnOffset');
locationOffset = locationOffset *0.01;
var eventStartDate = currentItemObject.RefinableDate00;
var targetTime = new Date(eventStartDate);
//get the timezone offset from local time in minutes
var tzDifference = locationOffset * 60;
//convert the offset to milliseconds, add to targetTime, and make a new Date
offsetTime = new Date(targetTime.getTime() + tzDifference * 60 * 1000);
//alert(eventStartDate + offsetTime);
}
}
},
function (s, a) {
console.error(a.get_message());
});
}function onError(error) {
alert("Error on retrieving current user location:" + error.responseText);
}
}
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
if(!$isNull(ctx.CurrentItem) && !$isNull(ctx.ClientControl)){
var id = ctx.ClientControl.get_nextUniqueId();
var itemId = id + Srch.U.Ids.item;
var eventStartDate = $getItemValue(ctx, "RefinableDate00");
var s = formatAMPM(new Date(eventStartDate.inputValue));
var eventEndDate = $getItemValue(ctx, "RefinableDate04");
var Location = $getItemValue(ctx,"RefinableString100");
if(Location != "") {} else {Location=Location; }
getUser(ctx.CurrentItem);
var startYear = new Date(eventStartDate.inputValue).format('yyyy');
var startDate = new Date(eventStartDate.inputValue).format('dd');
var startMonth = new Date(eventStartDate.inputValue).format('MMM');
var endYear ="";
var endDate = "";
var endMonth = "";
var endPMAM = "";
if(eventEndDate!="")
{
endYear = new Date(eventEndDate.inputValue).format('yyyy');
endDate = new Date(eventEndDate.inputValue).format('dd');
endMonth = new Date(eventEndDate.inputValue).format('MMM');
endPMAM = formatAMPM(new Date(eventEndDate.inputValue));
}
else
{
endYear = "endYear";
endDate = "endDate";
endMonth = "endMonth";
endPMAM = "EndAMPM";
}
var EventDivId = id + "EventContainer";
search.eventdate.init(ctx, EventDivId);
_#-->
<div class="content-news-item" >
<div class="content-news-item-icon">
<div class="content-news-item-icon-in">
<div class="content-news-icon">
<!-- _#= ctx.CurrentItem.PublishingImage =#_
<img src="_#= ctx.CurrentItem.PublishingImage =#_" width="570" height="270" alt="_#= $htmlEncode(ctx.CurrentItem.Title) =#_">-->
</div>
</div>
</div>
<div class="content-news-item-info">
<div class="content-news-item-date">_#= startYear + " "+ startMonth + " " + startDate + " To " + endYear + endMonth + " " + endDate =#_</div>
<div class="content-news-item-date">_#= s + " - " + endPMAM =#_</div>
<div class="content-news-item-date2">_#= Location =#_</div>
<div class="content-news-item-date2">_#= offsetTime + " offset time" =#_</div>
<div id="_#= $htmlEncode(EventDivId) =#_">
<div class="EventDateUserClass">
</div>
</div>
<div class="content-news-item-date2">
<a href='_#= _spPageContextInfo.webAbsoluteUrl + "/_vti_bin/owssvr.dll?CS=109&Cmd=Display&List=" + $htmlEncode(ctx.CurrentItem.RefinableString103) + "&CacheControl=1&ID=" + $htmlEncode(ctx.CurrentItem.RefinableString102) + "&Using=event.ics" =#_'>Add to OutLook</a>
</div>
<div class="content-news-item-title"><a href="_#= ctx.CurrentItem.Path =#_" class="slide-title">_#= $htmlEncode(ctx.CurrentItem.Title) =#_</a></div>
</div>
</div>
<!--#_
}
AddPostRenderCallback(context, function () {
$(".content-news-item-date2").css("color", "red");
alert("inside postrendercallback");
get(elmId);
});
_#-->
</div>
</body>
</html>