2

I cant believe that Sharepoint does not have a managed property for list name, neither a Crawled property I can map. Seems weird to me.

I have a display template that renders results in a Table Format. The column Number 5 renders the link to the library where the document is found and I have hardcoded the string Library.

This is not very useful if our site collection has 200 sites and 20 different libraries on each one.

How can I get the List Name? I see I have a list ID, but I am not sure if I can use custom js functions inside a display template?

<html xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882">
<head>
    <title>List Table Item</title>

    <!--[if gte mso 9]><xml>
    <mso:CustomDocumentProperties>
    <mso:TemplateHidden msdt:dt="string">0</mso:TemplateHidden>
    <mso:ManagedPropertyMapping msdt:dt="string">ListID','ListItemID','ContentTypeId','Link URL':'Path','Property 1':'Title','Property 2':'','Property 3':'','Property 4:'','Property 5':'','Property 6':'','Property 7':'','Property 8':'','Property 9':'','Property 10':'','FileExtension','SecondaryFileExtension'</mso:ManagedPropertyMapping>
    <mso:MasterPageDescription msdt:dt="string">This is the item row template, use this template in combination with the List Table Control template.</mso:MasterPageDescription>
    <mso:ContentTypeId msdt:dt="string">0x0101002039C03B61C64EC4A04F5361F385106603</mso:ContentTypeId>
    <mso:TargetControlType msdt:dt="string">;#Content Web Parts;#</mso:TargetControlType>
    <mso:HtmlDesignAssociated msdt:dt="string">1</mso:HtmlDesignAssociated>
    <mso:HtmlDesignStatusAndPreview msdt:dt="string">http://be-dmsgtsdev003.be.ema.pwcinternal.com/_catalogs/masterpage/Display Templates/Content Web Parts/Item_List_Item.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>
    <div id="TwoLines">
        <!--#_
        // Give up your names for the properties in the following array
        var propertyNames = {"Property 1":"File Name","Property 2":"Last modified by","Property 3":"Last modified date","Property 4":"Content type","Property 5":"Library"};

        var encodedId = $htmlEncode(ctx.ClientControl.get_nextUniqueId() + "_tableitems_");

        var linkURL = $getItemValue(ctx, "Link URL");
        var libraryLink = $getItemValue(ctx, "ParentLink");
          linkURL.overrideValueRenderer($urlHtmlEncode);
        var iconURL = Srch.ContentBySearch.getIconSourceFromItem(ctx.CurrentItem);

        var listID = $getItemValue(ctx, 'ListID');
        var listItemID = $getItemValue(ctx, 'ListItemID');
        var ContentTypeId = $getItemValue(ctx, 'ContentTypeId');



        var rowId = encodedId + "row";
        var editCellId = rowId + "_cell";

        var currentItemIdx = ctx.CurrentItemIdx + 1;
        var alternating = currentItemIdx % 2 === 0 ? "ms-alternating" : "";


        if (currentItemIdx === 1) {
        _#-->
        <thead>
            <tr>
                <!--#_
                // Show the file icon
                _#-->
                <th class="ms-vh-icon ms-minWidthHeader">
                    <img width="16" height="16" border="0" src="/_layouts/15/images/icgen.gif">
                </th>
                <!--#_

                // Show the properties that aren't empty
                for(var i = 1; i <= 10; i++) {
                    var property = $getItemValue(ctx, String.format("Property {0}", i));
                    if(property.managedPropertyName !== String.format("Property {0}", i)) {
                        var propertyName = typeof propertyNames[property.propertyLookupName] === "undefined" ? property.managedPropertyName : propertyNames[property.propertyLookupName];
                _#-->
                <th class="ms-vh2">
                    _#= propertyName =#_                     
                </th>
                <!--#_
                    }
                }
                _#-->
            </tr>
        </thead>
        <tbody>
            <!--#_
            }
            _#-->
            <tr id="_#= rowId =#_" class="_#= alternating =#_ ms-itmHoverEnabled ms-itmhover">
                <td class="ms-cellstyle ms-vb-icon">
                    <!--#_ if(!iconURL.isEmpty) { _#-->
                    <img src="_#= iconURL =#_" />
                    <span id="_#= editCellId =#_"></span>
                    <!--#_
                    } else {
                    _#-->
                    <img width="16" height="16" border="0" src="/_layouts/15/images/icgen.gif">
                    <!--#_
                    }
                    _#-->
                </td>

                <!--#_
                // Show the properties that aren't empty
                for(var i = 1; i <= 10; i++) {
                    var property = $getItemValue(ctx, String.format("Property {0}", i));
                _#-->
                <td class="ms-cellstyle ms-vb2">
                    <!--#_
                        if(!property.isEmpty)
                        {
                            var value = i === 1 ? String.format("<a href='{0}' class='ms-listlink'>{1}</a>", linkURL, property) : i === 5 ? String.format("<a href='{0}' class='ms-listlink'>{1}</a>", libraryLink, 'Library' ) : property;

                    _#-->
                    _#= value =#_
                    <!--#_
                            if (i === 1 && !listID.isEmpty && !listItemID.isEmpty && !ContentTypeId.isEmpty) {
                                var viewPropUrl = String.format('/_layouts/15/listform.aspx?ListId={0}&ID={1}&ContentTypeID={2}&Source={3}', listID, listItemID, ContentTypeId, window.location.href.split('#')[0]);
                    _#-->
                    &nbsp;&nbsp;
                    <span title="Open Menu" class="NotificationDiv ms-ellipsis-a" rel="_#= viewPropUrl =#_" ref="_#= property =#_" path="_#= linkURL =#_" style="cursor: pointer; margin-top: 3px; float: right;">
                        <img alt="Open Menu" src="/_layouts/15/images/spcommon.png" class="ms-ellipsis-icon">
                    </span>
                    <!--#_
                            }
                        }
                    _#-->
                </td>
                <!--#_
                }
                _#-->
            </tr>
            <!--#_
            if (currentItemIdx === ctx.CurrentGroup.RowCount) {
            _#-->
        </tbody>
        <!--#_
        }
        _#-->
    </div>
</body>
</html>
  • do you need the Current List Name or a collection of List inside a particular web ? – Akarsh Gupta Jan 15 '15 at 9:32
  • Also you can use Custom JS function inside your display template, see the below link. It will give you can idea to include JS libraries inside your display template and also how can you use them dotnetmafia.com/blogs/dotnettipoftheday/archive/2014/02/26/… – Akarsh Gupta Jan 15 '15 at 9:40
  • 1
    There isn't a managed property for that, you can only receive the list IDs via a managed property. What you could do when you are working on-premises is creating a content enrichment webservice to link the listname with the item. – Elio Struyf Jan 15 '15 at 20:15
  • thanks @ElioStruyf, long time! enjoying sun in Colombia!. Unfortunately in my new environment is not on premises, and showing the library name its very important. I know with JSOM I could get the list name by having the id, but I havent been succesful trying to integrate JSOM code into display templates. Maybe a good idea for one of your wonderful posts!!! – Luis Valencia Jan 16 '15 at 4:35
  • 1
    I would go for a REST approach, that is a bit less coding and you get all the information from the managed properties. I see what I can do. – Elio Struyf Jan 16 '15 at 8:11
3
+50

As I mentioned in the comment, the approach which I would suggest is via a call to the list REST endpoint to retrieve the title.

The endpoint to call is the following: tenant.sharepoint.com/_api/Lists(guid'4d46792d-0fd0-4850-aa29-4f3ea8310ac4')?$select=Title

Here is an example item display template of how I achieved it:

<html xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"> 
<head>
<title>Two lines - Listname</title>

<!--[if gte mso 9]><xml>
<mso:CustomDocumentProperties>
<mso:TemplateHidden msdt:dt="string">0</mso:TemplateHidden>
<mso:ManagedPropertyMapping msdt:dt="string">'Link URL'{Link URL}:'Path','Line 1'{Line 1}:'Title','Line 2'{Line 2}:'','FileExtension','SecondaryFileExtension','SPWebURL','ListID'</mso:ManagedPropertyMapping>
<mso:MasterPageDescription msdt:dt="string">This template shows the list / library name.</mso:MasterPageDescription>
<mso:ContentTypeId msdt:dt="string">0x0101002039C03B61C64EC4A04F5361F385106603</mso:ContentTypeId>
<mso:TargetControlType msdt:dt="string">;#Content Web Parts;#</mso:TargetControlType>
<mso:HtmlDesignAssociated msdt:dt="string">1</mso:HtmlDesignAssociated>
</mso:CustomDocumentProperties>
</xml><![endif]-->
</head>

<body>
    <script>
        Type.registerNamespace('search.listname');

        search.listname = function () {
            var itemInfo = {};
            var listInfo = {};

            var init = function (context, elmId) {
                // Store item info
                itemInfo[elmId] = {};
                itemInfo[elmId]["webUrl"] = context.CurrentItem.SPWebURL;
                itemInfo[elmId]["listId"] = context.CurrentItem.ListID;

                // Add an on post render callback, this will be excuted when all the results are rendered
                AddPostRenderCallback(context, function() {
                    get(elmId);
                });
            },
            get = function (elmId) {
                // Retrieve the item information
                var webUrl = itemInfo[elmId].webUrl;
                var listId = itemInfo[elmId].listId;

                if ($isEmptyString(webUrl) || $isEmptyString(listId)) {
                    return;
                }

                // Remove brackets from guid
                listId = listId.substring(listId.indexOf('{') + 1, listId.indexOf('}'));

                // Check if the list object exists, if it exists, an Ajax call is already initiated or performed
                if (typeof listInfo[listId] !== "undefined") {
                    // Check if the list name is retrieved
                    if (typeof listInfo[listId]["Title"] !== "undefined") {
                        // Write the list name to the listname element on the page
                        quickRender(elmId, listId);
                    } else {
                        // List name was not yet retrieved, set the list ID as class on the element
                        setClass(elmId, listId);
                    }
                    return;
                } else {
                    // Ajax call not yet initiated, create a new object for the list ID
                    listInfo[listId] = {};
                    setClass(elmId, listId);
                }

                // Do a Ajax call to retrieve the list / library title
                (function (elmId, listId) {
                    var request = new XMLHttpRequest();
                    var restUrl = String.format("{0}/_api/Web/Lists(guid'{1}')?$select=Title'", webUrl, listId);
                    request.open('GET', restUrl, true);
                    request.setRequestHeader('Accept', 'application/json;odata=nometadata');
                    request.setRequestHeader('Content-Type', 'application/json;odata=nometadata');
                    request.onload = function (e) {
                        if (request.readyState === 4) {
                            // Check if the get call was successful
                            if (request.status === 200) {
                                // List retrieved
                                var data = JSON.parse(request.response);
                                if ($isEmptyString(data.Title)) {
                                    return;
                                }
                                // Store the list name
                                listInfo[listId]["Title"] = data.Title;
                                // Render the list name
                                render(elmId, listId);
                            } else {
                                // No list found
                            }
                        }
                    };
                    request.onerror = function (e) {
                        // Catching errors
                    };
                    request.send(null);
                })(elmId, listId);
            },
            // Set the list ID as class name to the SPAN element
            setClass = function (elmId, listId) { 
                var elm = document.getElementById(elmId);
                if (!$isNull(elm)) {
                    var listElm = elm.getElementsByClassName('listname')[0];
                    if (!$isNull(listElm)) {
                        // Write the list name to the page
                        listElm.className = String.format('{0} {1}',listElm.className, listId);
                    }
                }
            },
            // Write the document title to all elements with the same list ID
            render = function (elmId, listId) {
                var elms = document.getElementsByClassName(listId);
                if (!$isNull(elms)) {
                    for (var i = 0; i < elms.length; i++) {
                        elms[i].innerHTML = listInfo[listId].Title;
                    }
                }
            },
            // Write the list name to the element
            quickRender = function (elmId, listId) {
                var elm = document.getElementById(elmId);
                if (!$isNull(elm)) {
                    var listElm = elm.getElementsByClassName('listname')[0];
                    if (!$isNull(listElm)) {
                        // Write the list name to the page
                        listElm.innerHTML = listInfo[listId].Title;
                    }
                }
            };

            return {
                init: init
            };
        }();

        Srch.U.registerRenderTemplateByName("listname_init", search.listname.init);
    </script>

    <div id="Listname">
<!--#_
var encodedId = $htmlEncode(ctx.ClientControl.get_nextUniqueId() + "_listname_");
var containerId = encodedId + "container";

// Listname init
Srch.U.getRenderTemplateCollection().listname_init(ctx, containerId);

var linkURL = $getItemValue(ctx, "Link URL");
linkURL.overrideValueRenderer($urlHtmlEncode);
var iconURL = Srch.ContentBySearch.getIconSourceFromItem(ctx.CurrentItem);

var line1 = $getItemValue(ctx, "Line 1");
var line2 = $getItemValue(ctx, "Line 2");
line1.overrideValueRenderer($contentLineText);
line2.overrideValueRenderer($contentLineText);

var pictureLinkId = encodedId + "pictureLink";
var pictureId = encodedId + "picture";
var dataContainerId = encodedId + "dataContainer";
var line1LinkId = encodedId + "line1Link";
var line1Id = encodedId + "line1";
var line2Id = encodedId + "line2";
_#-->
        <div class="cbs-Item" id="_#= containerId =#_" data-displaytemplate="Item2Lines">
            <a class="cbs-ItemLink" title="_#= $htmlEncode(line1.defaultValueRenderer(line1)) =#_" id="_#= pictureLinkId =#_">
                <img class="cbs-Thumbnail" src="_#= $urlHtmlEncode(iconURL) =#_" alt="_#= $htmlEncode(line1.defaultValueRenderer(line1)) =#_" id="_#= pictureId =#_" />
            </a>
            <div class="cbs-Detail" id="_#= dataContainerId =#_">
                <a class="cbs-Line1Link ms-noWrap ms-displayBlock" href="_#= linkURL =#_" title="_#= $htmlEncode(line1.defaultValueRenderer(line1)) =#_" id="_#= line1LinkId =#_">_#= line1 =#_</a>

                <strong>List / Library name:</strong> <span class="listname"></span>
<!--#_
if(!line2.isEmpty)
{
_#-->
                <div class="cbs-Line2 ms-noWrap" title="_#= $htmlEncode(line2.defaultValueRenderer(line2)) =#_" id="_#= line2Id =#_">_#= line2 =#_</div>
<!--#_
}
_#-->
                </div>
        </div>
    </div>
</body>
</html>

More information can be found on: Retrieving the list or library name of an search result in display templates

The template can be downloaded from GitHub: template on GitHub

Here is how it looks like:

Template result

0

You can use custom javascript in display templates. Javascript code should be within <!--#_ <JavaScript Code> _#-->

If you use SP.js reference you can get the List object using the getById method and through that find the List name? I haven't tried this but its worth a try imho.

PS: I didn't mean to post this as an answer but the system wouldn't let me post this asa comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.