I was looking at different ways to get the author of a publishing page in a Page Layout today. There is a control that SharePoint provides, which will give us the name of the author:
<SharePointWebControls:UserField FieldName="Author" runat="server"></SharePointWebControls:UserField>
But this only gets the display name. I really wanted to create a nice looking chip, using the authors image and with a mailto link. For that I needed the email address.
I grabbed a sample chip style and put together a bit of JavaScript and a call to spJsom.
Within a few minutes I had the page author in a chip. Done.
This code snippet relies on jQuery and spJsom
I uploaded spJsomFluent.js to a location in the Style Library of the Site Collection and put this into a ScriptEditor. However you could also put it in a publishing page layout.
<style>
.chip {
display: inline-block;
padding: 0 25px;
height: 50px;
font-size: 16px;
line-height: 50px;
border-radius: 25px;
background-color: #f1f1f1;
}
.chip img {
float: left;
margin: 0 10px 0 -25px;
height: 50px;
width: 50px;
border-radius: 50%;
}
</style>
<a class="chip" href="" id="authorLink"></a>
<script type="text/javascript" src="/sites/somesite/style library/scripts/spJsomFluent.js"></script>
<script type="text/javascript">
SP.SOD.executeOrDelayUntilScriptLoaded(function(){
var context = SP.ClientContext.get_current();
new spJsom.Fluent()
.withContext(context)
.listItem.get(context.get_web(), _spPageContextInfo.listTitle, _spPageContextInfo.pageItemId, ["ID", "Author"])
.execute()
.fail((sender, args) => {
console.error(args.get_message());
})
.done((results) => {
let listItem = results[0].result[0];
let userEmail = listItem.get_item("Author").get_email();
let userDisplayName = listItem.get_item("Author").get_lookupValue();
let userPhotoUrl = (_spPageContextInfo.siteServerRelativeUrl + "/_layouts/15/userphoto.aspx?size=S&accountname=" + userEmail).replace("//", "/");
$("#authorLink")
.attr("href", "mailto:" + userEmail)
.html("<img src='" + userPhotoUrl + "'> " + userDisplayName);
});
}, 'SP.js');
</script>