Tuesday, April 29, 2014

How-to display file format icons for Document Links

imageYou might have a document library which has the ability to add Link to a Document.

This is useful if you link in items from another document or information repository than SharePoint. Often the links will point to Office format files or PDF’s which is all good, and they display just fine in the document library with icons.





image

You see the PDF icon with a small arrow overlayed. These are actually two images, one for the icon and one for the arrow.

Once you go to the search page the story is different. icons does not show as the links themselves are stored as .aspx files in the library.
image

To fix this I created a custom display template and a result source.

As I’m a bit on the lazy side I decided to reuse the default templates and took a copy of Item_Default.html and Item_CommonItem_Body.html and named them Item_DocumentLink.html and Item_DocumentLink_Body.html.

In order to pull out the file extension for the link you have too look at the managed property  URLOWSURLH, so I added this to both display templates.

The trick to link these together is to add the following below the <body> tag, where you have to change the path to where you uploaded the files.

<script>
    $includeScript(this.url, "~sitecollection/_catalogs/masterpage/Display Templates/mAdcOW/Item_DocumentLink_Body.js");
</script>

and you also have to replace _#=ctx.RenderBody(ctx)=#_ with

_#= CoreRender(Srch.U.getRenderTemplateByName("~sitecollection/_catalogs/masterpage/Display Templates/sit/Item_DocumentLink_Body.js", ctx), ctx) =#_

The next part is to update Item_DocumentLink_Body.html to add the logic for icon rendering. In addition to adding the managed property URLOWSURLH, I added the following code above the line:

if (!$isEmptyString(ctx.CurrentItem.csr_Icon)) {

if($isEmptyString(ctx.CurrentItem.csr_Icon) && !$isEmptyString(ctx.CurrentItem.URLOWSURLH)) {
    var ext = ctx.CurrentItem.URLOWSURLH.split(".").pop().split('?')[0];
    var extObj = new Object();
    extObj["FileExtension"] = ext;

    var iconUrl = SP.Utilities.HttpUtility.htmlEncode(Srch.U.ensureAllowedProtocol(Srch.U.getIconUrlByFileExtension(extObj, null)));
    ctx.CurrentItem.csr_Icon = iconUrl;
}

Now I have the display template ready and have to wire it up to a result source.

I named my result source Document Link, made it trigger on ContentType equals Link to a Document, and picked by new Document Link display template.


image


I also checked the Optimize for frequent use checkbox to make sure my new managed properties indeed work.

Back at the search page, I now get the icon for the pdf file. Further improvements would also add the arrow overlay to indicate a link.

image

The full code of the templates will be uploaded to https://github.com/SPCSR/DisplayTemplates once it’s all set up.