I am using a custom display template for Content search web part. I am able to get currentItem's properties but how to get logged in user's username using client slide rendering.
2 Answers
You can get logged in user by a GET request.
$.ajax({
async: false,
headers: { "accept": "application/json; odata=verbose" },
method: "GET",
url: formCtx.webAttributes.WebUrl + "/_api/web/CurrentUser",
success: function (data) {
currentUser = data.d;
}
});
Now use currentUser
in your CSR code. You may omit async if you can handle it properly.
_spPageContextInfo.userLoginName
will give you the current user's login name. So you can use it inside your CSR code if you need the login name only.
-
Use of
async : false
is deprecated. Anyways thanks your solution but you are using REST api whereas I was looking for a solution in which I don't have to use async calls, something which is already availble likectx.CurrentItem.ListItemId
– YayatiCommented Oct 5, 2015 at 10:55 -
Which information of current user you need actually? _spPageContextInfo.userLoginName will give u the current user's login name. If you need more information, then REST API is the only way I guess. You need not to use async:false necessarily. You can write your CSR code inside success function or when this request is done Commented Oct 5, 2015 at 11:20
-
I want to get user
Title
. If I call REST api code in display template, the async query gets called for each Item. Is there any way of executing REST call for only once and later use its result while iterating in each item ?– YayatiCommented Oct 5, 2015 at 11:50 -
Of course! just execute your REST API code outside CSR code. Then save your current user into a global variable and use it later on Commented Oct 5, 2015 at 12:04
I am doing this quite similar. Here my script:
<script type="text/javascript">
$(document).ready(function() {
var loginName = "";
var userid = _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : onSuccessA,
error : onErrorA
});
function onSuccessA(data, request){
console.log(data.d);
loginName = data.d.Title;
alert("Current User is: " + loginName);
}
function onErrorA(error) {
alert(error);
}
});
</script>
If you check the output in console.log
you can see a bunch of options you get with this ajax request.