Refine search results by Managed Metadata - Part 3 (Code)
Part 3 of the blog series explains the code. My explanations are limited to the major changes compared to Elio Struyf's blog article (see URL's in Part 1).
I used Visual Studio code to develop the code. Code changes are copied directly to the relevant folders in SharePoint Online and checked in via the Gulp plugin gulp-spsave. You can view the complete code in my GitHub archive.
1/ REFINER DISPLAY TEMPLATE
The refiner loads all terms in the Managed Metadata Termstore for the Term Set ID specified in the code. Since the term structure can be very extensive, the term tree is loaded only once. This improves usability and avoids unnecessary calls to SharePoint.
// Check if refiner has already been loaded and save the div to avoid reloading termstore items var refinerAlreadyLoaded = false; var elementMMRefiner = document.getElementById("Container"); if (elementMMRefiner) { var elementMMRefinerInnerHTML = elementMMRefiner.innerHTML; refinerAlreadyLoaded = true; } if(!refinerAlreadyLoaded){
setTimeout(function(){refiner.mm.taxid.addDiv(elementMMRefiner)},20);
The method addDiv inserts the previously saved div tag with the terms.
var addDiv = function (elementMMRefiner) { var domEmptyContainer = document.getElementById("Closing"); //domEmptyContainer.innerHTML += "AddedText"; domEmptyContainer.parentNode.insertBefore(elementMMRefiner, domEmptyContainer); }
2/ ITEM DISPLAY TEMPLATE
To display the terms of an item, the Managed Property (here: RefinableString00) is added to the header.
<mso:ManagedPropertyMapping msdt:dt="string">'Title':'Title','Path':'Path','Description':'Description','EditorOWSUSER':'EditorOWSUSER','LastModifiedTime':'LastModifiedTime','CollapsingStatus':'CollapsingStatus','DocId':'DocId','HitHighlightedSummary':'HitHighlightedSummary','HitHighlightedProperties':'HitHighlightedProperties','FileExtension':'FileExtension','ViewsLifeTime':'ViewsLifeTime','ParentLink':'ParentLink','FileType':'FileType','IsContainer':'IsContainer','SecondaryFileExtension':'SecondaryFileExtension','DisplayAuthor':'DisplayAuthor','RefinableString00':'RefinableString00'</mso:ManagedPropertyMapping>
The method getMMValues gets the tagged terms of the item.
Type.registerNamespace('displaytemplate.mm'); displaytemplate.mm = (function () { var getMMValues = function (stringToEvaluate) { var resultString = " "; var countLO = (stringToEvaluate.match(/L0/g) || []).length; var stringToEvaluateArray = stringToEvaluate.split(";"); var itemNumber = 1; stringToEvaluateArray.forEach(function(element) { if (element.startsWith("L0")){ var elementArray = element.split(/[\s|]+/); resultString = resultString + elementArray[elementArray.length-1]; if (itemNumber < countLO){resultString += ", "}; itemNumber++; } }, this); return resultString } return { getMMValues: getMMValues } })();
Thanks for reading and stay tuned for Part 4: Steps.
Any questions or remarks? Please leave a comment.