Wednesday, June 26, 2013

SP Javascript function getIconUrlByFileExtension

In XSL the function ‘ddwrt:MapToIcon’ would return the icon file name for the given extension, based on the mapping in the DOCICON.XML file. In SharePoint 2013 there is a similar function available in JavaScript:
Srch.U.getIconUrlByFileExtension(arg1, arg2)

This function needs an object as an input parameter. In JavaScript it is very easy to create a fake object. In the context of a display template for refiners, we just add a property called FileExtension to the object and give it the Refinement Name value of the File Extension refiner.

fakeObject = new Object();
fakeObject.FileExtension = filter.RefinementName;

For some reason not all of the standard File Extensions are recognized by this function and return the standard icon file html16.png. Therefore we are going to use the second -optional- input parameter of the JavaScript function to define what it should be in case of "if no mapping is found". We can construct the path of the standard icon files in the images folder of the server file system, or use a library in the search center site collection itself to store the custom icon files. In this case we will use the images folder.

var urlIcon = Srch.U.getIconUrlByFileExtension(fakeObject, "/_layouts/15/images/ic" + filter.RefinementName + ".gif");

To show the icon inline with the refiner value we just add an image element to the Html part of the display template.

<img class="ms-srch-item-icon ms-positionRelative" src="_#= $urlHtmlEncode(urlIcon) =#_" onError="this.src='_#= SP.Utilities.VersionUtility.getImageUrl('generaldocument.png') =#_';" />

We are able to use the ‘onError’ event of the IMG element as a safety net in case the path of an icon file doesn’t exists. We will use another JavaScript function from SharePoint to retrieve the url of the image file for a general document:
SP.Utilities.VersionUtility.getImageUrl('generaldocument.png')

In this way we are able to use the function getIconUrlByFileExtension and have two alternatives in case it would not return the proper icon file.

1 comment:

  1. It works like charm. Great post. Thanks for the post.

    ReplyDelete