Showing No Results with PnP Search

PnP Modern Search web parts are awesome. It’s surprising that the out-of-the-box features of SharePoint Online haven’t yet caught up to the capabilities the community has provided, but nonetheless, these web parts will have you bridging the gap between search customization of yesteryear (On-Premises SharePoint) and now (SharePoint Online) in no time.

One of many great parts about the PnP Search Results web part is the various layouts that come out of the box, including:

  • Details List
  • Cards
  • Slider
  • List
  • Debug
  • Custom
  • People
While I find all of these layouts to be helpful, depending on the situation, one thing I noticed about utilizing them was that I could “hide this web part if there’s nothing to show” (see figure 1) but that option couldn’t differentiate between “no results” and “the user hasn’t searched yet”.

Figure 1

Alas, the customizations available in this web part, via Handlebars, came to my aid.

The issue with the “Hide this web part if there’s nothing to show” is that the web part will be hidden when there are no results, which can occur when the user’s search yields no results, or the user hasn’t yet searched. For the latter, turning this option on works, as the web part will display nothing until the user searches. For the former, however, this means that a search yielding no results won’t give any kind of notification to the user that what they’ve searched for has no results.

The solution is to leave the “Hide this web part if there’s nothing to show” option off and edit the “results template” (figure 2) so that you can differentiate between a blank search and no results.

Figure 2

To make this update, click the “{}” button next to the results template, and just before the {{#if @root.properties.showResultsCount}} add the following:

{{#if ( not (eq @root.inputQueryText undefined ) ) }}
After the the {{/if}} statement for the {{#if @root.properties.paging.showPaging}} statement, add another {{/if}} statement to close out your newly entered ‘if statement’.
{{/if}}

What we are doing is telling the template to only yield the results, including the number found, if the search query isn’t undefined (blank). This is a quick update to the template and will work with the various layouts available in the web part.

I hope that you’ve enjoyed this article and it helped saved you some time while working with this great web part.

Cheers,
Matt

Add a Comment

Your email address will not be published. Required fields are marked *