Integrating Search-Driven Content
In Chapter 1, we introduced new features in SharePoint 2013 that use the power of search to surface dynamic content across sites. SharePoint 2013 is the first release of SharePoint to fully integrate FAST search into the core product. In this chapter, we learn how to integrate dynamic content from other sites and present the content with the same user interface by utilizing new out-of-the-box search web parts as well as HTML, JavaScript, CSS, display templates, query rules, and result types. We first review how to get content from other sites by using the new SharePoint 2013 cross-site publishing feature. Then we create a content rollup solution by creating custom display templates for SharePoint’s Content Search web part. Last, we look at how to fine-tune search queries and customize the display of results in search. We demonstrate how to use query rules and result types to improve the search experience.
Our Scenarios
For the public Specter Group site, we have two scenarios that use search-driven content.
In the first scenario, we want to show potential buyers a rollup of all the available Specter Group properties for sale from all the communities, such as floor plans, description, and property type. Because only builders and architects at Specter Group can author and manage floor plans, we want to have a dedicated and separate site just for floor plans (www.spectergroup.com/sites/floorplan). Meanwhile, we want to present all the floor plans to site visitors of www.spectergroup.com in a seamless manner. To accomplish this, we need to perform the following steps (for a process diagram of the scenario, refer to Figure 9-1):
In this chapter, we focus on the design and the implementation of the solution for this scenario. First we demonstrate how to pull the floor plan content from the Floor plan site collection. Then, we will show how to customize the content search web part on the Floor Plans page to display search results with our own design using custom display templates.
Figure 9-1. Content publishing process for Spectergroup.com floor plans
In the second scenario, we want to customize the search experience when users search for “floor plans”. We are going to create a query rule and a result type for floor plans, such that when users search for the keyword “floor plans”, the following things happen:
In this chapter, we look at how to fine-tune search queries and customize the display of floor plan results in search. We demonstrate how to use query rules and result types to improve the search experience.
Publishing Content to Search
In Chapter 8, we used the Cross-Site Collection Publishing feature to allow http://spectergroup.com to consume publishing pages and page layouts from http://authoring.spectergroup.com. For more information on how to set up cross-site publishing, refer to Chapter 8. In this chapter, we look at how to use the Cross-Site Collection Publishing feature to consume content, such as documents. Then in the section “Custom Display Templates for Specter Design” later in this chapter, we demonstrate in detail how to customize the display of results by creating custom display templates.
Note Learn how to configure and use Cross-Site Collection Publishing in Chapter 8.
Configuring Content for Search
Before we can consume the floor plan content, we need to make sure the content is available to SharePoint search. The floor plan content resides in a picture library called Specter Group Community Floor Plans in the http://spectergroup.com/sites/floorplan site collection. Table 9-1 shows the metadata that describes a floor plan document. For more information on Specter Group TermSets and the Managed Metadata feature, refer to Chapter 7.
Table 9-1. Specter Group Community Floor Plan Metadata
As shown in Table 9-1, all floor plan documents have a set of properties that describe each floor plan. Because we are working with search, we need to think about how to expose these properties to SharePoint search so that users can search against them and view these properties in the search results. To ensure these properties can be searched against and can be used as refiners and filters, we need to create Search Managed Properties for each floor plan property. To learn how to create managed properties, refer to the section “Creating Search Managed Properties for Content” later in this chapter, where we demonstrate how to create a search managed property, SpecterPropertyType, based on the Managed Metadata column property type. We later use the SpecterPropertyType managed property as a refiner and a filter in our solution.
As floor plan files are added to the library, users identify and tag metadata (such as Community Name and Property Type information) for each file (see Figure 9-2).
Figure 9-2. To enhance search ability of content, tag content with metadata when authoring content
Once the content is ready for publishing, we need to enable the content’s library as a catalog. For the purpose of demonstration, please refer to Chapter 7 for detailed steps for configuring a catalog.
Note Before we can enable a library as a catalog, we need to enable the Cross-Site Collection Publishing feature. For more information on how to get started with Cross-Site Collection Publishing and how to configure a library as a catalog, refer to Chapter 8.
After we configure the catalog, the Catalog Settings page should look like Figure 9-3, which shows the top section of the page.
Figure 9-3. Catalog Settings page for Specter Group Community Floor Plans document library
Once the catalog is created, before this content becomes available for consumption from other site collections, we must perform a full or an incremental crawl on the content source.
Figure 9-4. Perform a full or an incremental crawl to get all new content and updates in search index
To ensure the target site gets fresh and up-to-date content, we need to configure the Search Service application to make sure SharePoint search is continuously crawling content in the authoring site, as seen in Figure 9-5. For more information on how to configure and schedule full crawl, incremental crawl, and continuous crawl in SharePoint search through Central Administration, refer to http://sprwd.com/6uhfguy.
Figure 9-5. From Central Administration, enable continuous crawls on the content source that contains this catalog to ensure freshness of the content
Tip Cross-site publishing is dependent on the search feature to index the content. New and updated content is only available for consumption after it has been crawled. In a production environment, we need to make sure SharePoint search is continuously crawling the authoring sites to get the latest content to appear in the consuming sites quicker. If the Search Service application gets corrupted or gets deleted for some reason, we need to configure the consuming site to reconnect to the catalog to reestablish connection with the content.
Creating Search Managed Properties for Content
Now that we have the content and the properties of the content available in the search index, we can create search managed properties for each property we want to use as refiners and filters.
Figure 9-6. Enable full indexing of content in the library
Figure 9-7. Mark the library for a full crawl during the next scheduled crawl
Figure 9-8. Navigate to SharePoint Central Administration's current Search Service application
Figure 9-9. Click Search Schema to view Managed Properties page
Figure 9-10. Create a new managed property from the Managed Properties page
Figure 9-11. Create new managed property page
Figure 9-12. Mark the new managed property as searchable
Figure 9-13. Mark the new managed property as queryable
Figure 9-14. Mark the new managed property as retrievable
Figure 9-15. Mark the new managed property to allow multiple values to be mapped
Figure 9-16. Mark the new managed property as refinable
Figure 9-17. Map the new managed property with a crawled property
Figure 9-18. Find the crawled property, then map to it
Figure 9-19. Quickly find the new managed property and view its properties
Figure 9-20. Start a full crawl to get values for the new managed properties
Getting Content from a Catalog
Now that we have the content as well as new managed properties in the search index, we need to make the content available for users to see in the Specter Group public-facing site. For our scenario, we need to enable the Specter Group public-facing site to connect to the Floor Plan catalog created in the previous section.
Figure 9-21. From the Specter Group public-facing site, connect to the published Floor plan catalog
Note For more information on how to configure and connect to a catalog, refer to Chapter 8.
Figure 9-22. Connect to the catalog without integrating navigation
Figure 9-23. Make catalog item's URL relative to the Specter Group public-facing site
Note For more information on how to create catalog item pages for a catalog, refer to Chapter 8.
Creating a Content Rollup Solution
In the following sections, we create a page for content rollup. We add a Content Search web part and configure it to get the right results by using the Query Builder.
Creating a Landing Page for Floor Plans
First, we need to create a landing page for our floor plans so that users can view all floor plans by navigating to the http://spectergroup.com/communities/floor-plans URL or by clicking Floor Plans on the Home Page menu flyout as shown in the wireframe in Chapter 3 and Figure 9-24.
Figure 9-24. Wireframe for Floor Plans landing page and menu flyout
Figure 9-25. Create a new landing page for Floor Plans
Figure 9-26. Add a new term for Floor Plans under the Communities term in the global navigation TermSet
Note For more information on how to configure navigation using the Managed Navigation feature, refer to Chapter 6.
Figure 9-27. Configure the page’s friendly URL by clicking the Page URLs icon
Figure 9-28. On the Page URLs page, add a friendly URL that maps to the Floor Plan term in the navigation TermSet
Exposing Search Results Using Content Search Web Part
Now that we have the Floor Plan’s landing page as well as its friendly URL configured, we need to add the Content Search web part to the page to display all the results from the Floor Plan catalog.
Figure 9-29. To add a web part to a page, we must first edit the page
Figure 9-30. Add a Content Search web part to the content rollup page
Figure 9-31. To configure the web part, we must select Edit Web Part
Now that we have the Content Search web part on the page, we next need to configure the web part.
Query Building
The Content Search web part allows you to restrict the results by limiting the query to a given set of content, whether it’s content from the search index or content from the site collection. To get to the right content, we need to formulate the query just right and we need to ensure the query works under different dynamic conditions for different users.
Figure 9-32. Click Change query to launch Query Builder
The full-screen Query Builder allows users to create and test queries without having to learn keyword query syntax. It shows a real-time preview of the search result on the right. It is also fully integrated with result sources and query rules. The web part allows dynamic values to be substituted at query time to enable query by dynamic values such as the current user’s profile properties or the current web’s properties.
Figure 9-33. In Query Builder, select a result source for its query
Figure 9-34. Select a resource source as the default source for the site
Figure 9-35. In Query Builder, select a result source and specify terms to limit the query. The Search result preview automatically updates as the the query changes
Figure 9-36. Define sort order for results
Figure 9-37. Select refiners to use for your results
Figure 9-38. Using managed properties as refiners will filter out search results
Figure 9-39. System-generated query based on configurations specified in Query Builder
Introduction to Display Templates
SharePoint 2013 uses Display templates in search web parts to display search results. Each display template controls what managed properties to show and how to render them in the web part.
Note Display templates are only available to Search web parts. For example, the Content Query web part cannot use display templates because it is not search-driven.
Display templates can be used to control the format and presentation of search results. We can also use display templates when we want to customize how content displays on our site. There are two major types of display templates: Control and Item (see Figure 9-40).
Figure 9-40. In the Content Search web part configuration tool pane, select a Control display template and an Item display template for the web part
Less common types of display templates include the Hover over template and the Filter template. Hover over templates are used to customize the look and feel of an item to show additional values when users hover over the result. For example, hover over templates for people results show additional user profile properties and hover over templates for document results show document previews. Filter templates are used when you want to show options for filtering the search results by configuring the refiners.
Out-of-the-Box Display Templates
SharePoint offers various out-of-the-box display templates to provide rendering of results.
Figure 9-41. From the list of out-of-the-box Control display templates, select the List Control display template to use for the rendering of the structure of the entire result set
For out-of-the-box Control display templates, List with Paging is useful when dealing with a large result set that needs to be displayed across multiple pages. The Content Search web part has a limit of displaying 50 items per page. The Slideshow Control display template is useful when dealing with images in the result set, such that they can be displayed in a slideshow format.
Figure 9-42. From the list of out-of-the-box Item display templates, select the Large picture Item display template to use for the rendering of a result item
The Large picture Item display template shows all the results in a single-column list with a thumbnail image as well as a hover-over effect.
Although for our scenario, we are using the Large picture display template, note there are other out-of-the-box Item display templates:
Note For more information on all different types of out-of-the-box display templates, refer to http://sprwd.com/5nbp9ss.
Figure 9-43. Floor Plans page with out-of-the-box display templates
We have configured the Content Search web part to get the right results from the Floor Plan catalog to appear on our Specter Group public-facing site and we have demonstrated the look and feel with out-of-the-box display templates. Let’s enrich the end user experience. In SharePoint 2010, if you wanted to change the look and feel of a particular search result item, it required a lot of work to modify the XSLT of the Core Results Search web part. Now we have the ability to craft the perfect look in HTML, CSS, and JavaScript by creating custom display templates in SharePoint 2013.
Before we create custom display templates, let’s review the design we would like to use for our floor plan page and the different components of the design. Figure 9-44 shows the design wireframe from Chapter 3 that we use to display the floor plans.
Figure 9-44. Design wireframe for the floor plan landing page as described in Chapter 3
This wireframe is the design we want to apply to the floor plans. The different components of the design are listed in Table 9-2. The list describes markup of all the components as well as how each component can be mapped into SharePoint.
Table 9-2. Design Components and Mappings in SharePoint
Because we have covered how to create custom master pages in Chapters 4 and 5, we focus here on the rest of the components in the design.
Display templates are used to tell SharePoint what content we want to show and how we want the content to be rendered on the page dynamically. During runtime, SharePoint renders HTML tags and CSS class to render the search results based on the configurations in the display templates. Before we dive into creating custom display templates, we need to first understand how we are styling our results so that they look like the wireframe design. Display templates render results as an HTML list, made of a <ul> tag and many <li> tags for each result item. To style the result set and each item in the set, we need to add a CSS class to style them.
To reference the CSS used for each design component, use the numbered items in Figure 9-45 and reference the corresponding Listings as outlined here.
Figure 9-45. CSS for each design component to style the result set
As we described in Table 9-2, we have style elements for the entire result set. To set the width of the entire result set and the layout of the results in a table layout, add the following CSS for the <ul> tag with the feature class.
Listing 9-1. CSS to Set the Width and Layout of the Entire Result Set
.feature {
width: 940px;
display:table;
}
Each item in the list has a CSS class to reference for its style. To set the background and width for each item and to set the layout of the results as inline-block so that results are rendered in a three-column table, add the following CSS for the <li> tags under the <ul> tag with the feature class.
Listing 9-2. CSS to Set the Background, Width, and Layout of Each Item in the Results List
.feature li {
background: #333333 none;
margin-bottom: 20px;
margin-left: 13px;
position: relative;
width: 300px;
display:inline-block;
}
To configure the display of the thumbnail of each item, we need to add the following CSS to style.css.
Listing 9-3. CSS to Set the Display of Thumbnail Images of Each Item
.feature li .thumb {
display: block;
position: relative;
width: 280px;
margin: 10px;
}
.feature li .thumb img {
max-width: 100%;
}
To configure the style of the caption and padding for the caption under the thumbnail of each item, add the following CSS.
Listing 9-4. CSS to Set the Style of Caption for Each Item
.feature li .caption {
padding: 20px 10px 20px 10px;
text-align: center;
color: #fff;
}
To configure the style of the background area for the date and month values for each item, add the following CSS. Note, border-radius creates the top semicircle.
Listing 9-5. CSS to Set the Style of the Date for Each Item
.feature li .thumb .date {
background: none repeat scroll 0 0 #fff;
display: block;
position: absolute;
left: 110px;
bottom: -25px;
width: 60px;
height: 50px;
float: left;
padding-top: 10px;
font-family: mensch;
border-radius: 40px;
-moz-border-radius: 40px;
-webkit-border-radius:40px;
}
.feature li .thumb .date div {
display: block;
font-size: 20px;
line-height: 20px;
text-align: center;
}
Custom Display Templates for Specter Design
In the previous section, we walked through the steps of implementing our design with an HTML list of items. Now, let’s see how we can integrate the design into SharePoint by creating custom display templates that can be used by the Content Search web part.
Before we dive into implementations of our own display templates, let’s review the basics of working with display templates.
Display Template Hierarchy
As discussed earlier, SharePoint uses two basic types of display templates to render results. When the Control display template and the Item display template are combined, the HTML output generated looks like Figure 9-46.
Figure 9-46. HTML output after adding a Control display template and an Item display template
To see what a Control display template generates during runtime, from your browser, inspect the entire result set on the page by clicking on the border of the result set. As you can see in Figure 9-47, the out-of-the-box Control_List Control display template (used in the previous section) renders a <ul> tag with the cbs-List class, which is included in the Searchv15.css file. This display template tells SharePoint the layout and structure of the results.
Note The content inside of the <ul> tag is configured by the Item display template and the hover over content is configured by the Hover display template.
Figure 9-47. The Control_List Control display template renders a <ul> element with the cbs-List class for the layout of the results on the page
Similarly, to see what an Item display template generates during runtime, from your browser, inspect a result item on the page by clicking on the border of the item. As you can see in Figure 9-48, the out-of-the-box Item_LargePicture Item display template (used in the previous section) renders an empty <li> tag, and under the <li> tag, there is a <div> tag with the cbs-largePictureContainer class, which is included in the Searchv15.css file. This display template tells SharePoint what properties to display for the item and how to display it.
Figure 9-48. The Item_LargePicture Item display template renders an empty <li> element, and under the <li> element, there is a <div> tag with the cbs-LargePictureContainer class for each result item on the page
Display templates work in a hierarchy in the following order:
Each level in the hierarchy has an associated content type in the Master Page Gallery. To identify the content type for each display template file, use the appropriate prefix in the file name. For example, Control_ListWithPaging.html and Control_ListWithPaging.js are files associated with the List with Paging Control display template residing in the Master Page Gallery. To find all the files associated with an out-of-the-box display template, we can follow this file naming convention to find the associated files in the Master Page Gallery.
In Figure 9-49, there is a list of out-of-the box Control display templates in the Display Templates folder under the Master Page Gallery. Note that when configuring the Content Search web part, each option in the Control display template drop-down list maps to an HTML display template file in the Master Page Gallery. For example, from the editor pane of the Content Search web part, the List with Paging option refers to the Control_ListWithPaging.html and Control_ListWithPaging.js files and the Slideshow option refers to the Control_Slideshow.html and the Control_Slideshow.js files.
Figure 9-49. Out-of-the-box Control display templates
Note All display templates consist of an HTML file and a SharePoint-generated JavaScript file. When creating or updating a display template, we should always modify the content in the HTML file, never the JavaScript file. Once the changes are made in the .html file, SharePoint compiles the changes into a .js file that has the same name as the .html file. SharePoint uses the new .js file to render the web part on the page. In the HTML file, we can add placeholders for where the managed properties and custom properties created in JavaScript should be displayed, and then SharePoint will emit the values during runtime.
Figure 9-50 shows a list of out-of-the-box Item display templates. Note that each one of these files maps to an option in the Item drop-down list below the Display Templates section in the configuration pane of the Content Search web part; for example, the Large picture option map to the Item_LargePicture.html and Item_LargePicture.js files and the Picture on left, 3 lines on right option map to the Item_Picture3Lines.html and Item_Picture3Lines.js files.
Figure 9-50. Out-of-the-box Item display templates
Note For the purpose of this chapter, we are focusing on display templates for Content web parts. If you want to learn more about all the display templates and their HTML and JavaScript files, including display templates for Search and Refiners, refer to http://sprwd.com/5nbp9ss.
As a side note, when we configure to consume a catalog from a publishing site, if we choose to let the catalog integration process create category pages, then the default category page created by SharePoint contains a Content Search web part. The default Control display template for the Content Search web part on the default category page is List with Paging, which is mapped to the Control_ListWithPaging files in the Master Page Gallery. The default Item display template used by that Content Search web part is Picture on top, 3 lines on bottom, which is mapped to the Item_Picture3Lines files in the Master Page Gallery.
Creating a New Display Template
The recommended approach to create a custom display template is to create a new HTML file for a new display template that is based on an existing display template. We do not want to override any out-of-the-box display templates because we want to keep the out-of-the-box design intact in case we want to use it again or use it as a reference design.
There are four components to implement when creating a custom display template.
Note To create a new display template, always make the changes in the .html file; never make any changes directly in the .js file. For the conversion process to succeed, always make sure the .html file is XML compliant. For example, unclosed tags such as <br> instead of <br/> will make the HTML file XML noncomplaint.
For our custom display template, first we make a copy of an existing display template that has the same Content type and is similar to the look and feel we want to create. Based on our design as described in the section “Specter Design Components” earlier in this chapter, we need to customize how the entire search result set looks as well as the rendering of each individual search result. Therefore, we need to create a custom Control display template and a custom Item display template.
Note We do not get the full WYSIWIG experience in our HTML editor as we do not get the style sheets and images used in the site.
Display Template Structure
Before we make any changes to our custom display templates, let’s review the basic structure of a display template. Please follow along with this section by referencing the local copy of the custom display template file. There are four main sections of a display template:
Figure 9-51. An example of the Title section in display templates
Listing 9-6. An Example of the ManagedPropertyMapping Element in Display Templates
<mso:ManagedPropertyMapping msdt:dt="string">
'LastModifiedTime':'LastModifiedTime',
'Specter Property Type'{Specter Property Type}:'SpecterPropertyType',
'Picture URL'{Picture URL}:'PublishingImage;PictureURL;PictureThumbnailURL',
'Link URL'{Link URL}:'Path',
'Line 1'{Line 1}:'Title',
'Line 2'{Line 2}:'Description',
'SecondaryFileExtension',
'ContentTypeId'
</mso:ManagedPropertyMapping>
Note Not all elements are used in every display template. For a list of CustomDocumentProperties elements, refer to http://sprwd.com/79gd4jr. To learn more about the ManagedPropertyMapping element, refer to the section “Creating Search Managed Properties for Content.”
$includeScript(this.url, "∼sitecollection/_catalogs/masterpage/custom.js");
To add a reference to an outside CSS file that is in a location relative to the current display template, we need to do the following:
$includeCSS(this.url, "../../style.css");
Note To learn more about how to add content to the DIV section, refer to Listing 9-11.
Basics of Working with JavaScript, HTML, and CSS
When creating custom display templates, we often need to work with JavaScript, HTML, and CSS to provide customizations. To see examples of how these are used, refer to the following two sections.
Inline JavaScript is very useful when we need to create variables to hold data and then output values in the HTML markup. When creating inline JavaScript in display templates, for it to execute, we need to add the JavaScript code after the first <div> tag in the template and it needs to be added between an opening and closing tag set. This is specific to display templates.
<!--#_ and _#-->
In HTML markup, to view the value of a managed property or a variable created from inline JavaScript, we need to enclose the code in an opening and closing tag set.
_#= somefield =#_
To access the current SharePoint context, use the ctx object. To access information of the current search result item, use the ctx.CurrentItem object. This object contains references to all of its managed properties. To get a managed property’s value of a result item, use the following in the HTML section:
_#=ctx.CurrentItem.SpecterPropertyType=#_
To work with managed properties as local variables in JavaScript, we can reference the property as follows:
var myPropertyType = "This is for property type: " + ctx.CurrentItem. SpecterPropertyType + ".";
Tip When creating the display template, it’s much faster and easier to test the look and feel by keeping the style tags under the <style> tag in the <head> section of the display template. Once the design is completed, we can move the style tags to a separate CSS file, then reference the CSS file in the <script> tag.
Creating a Custom Control Display Template
For our scenario, let’s see how we can integrate the design we have implemented in the section “Specter Design Components” earlier in this chapter with our custom display templates. Let’s start with the Control display template.
Figure 9-52. Define a name for the custom Control display template
Recall from Chapter 4 that we created a custom style sheet, style.css, which contains custom styles for the site. The file was then added to the Specter Group public-facing site’s Master Page Gallery and has been included in the master page so that it can be referenced throughout the site.
Listing 9-7. Add the Feature Class to the <ul> Tag to Ensure Results Are Displayed in a Three-Column Table
<ul class="feature">
_#=ctx.RenderGroups(ctx) =#_
</ul>
Figure 9-53. Properties to set when uploading a custom display template file to the Master Page Gallery
Figure 9-54. New display template is added to the Control display template drop-down list in the web part
Creating a Custom Item Display Template
Next, we customize the rendering of each search result by creating our own Item display template.
From the top of the Item_LargePicture.html page we created in a prior section, the value inside the <title> tag is the name displayed in the Item display template drop-down list when configuring the Content Search web part. We change it to Specter Large picture as in Figure 9-55.
Figure 9-55. Define a name for the custom Item display template
With the Item display template in place, next we need to tell the display template what to display for each item and how to display it.
Adding Search Managed Properties
Every Item display template contains information about the managed properties it needs to display. To update the managed properties referenced in the display template, we need to change the value of the ManagedPropertyMapping field, as shown in Listing 9-8. We need to add a tag called mso:ManagedPropertyMapping to include any out-of-the-box managed properties as well as any custom managed properties we have created in search (such as the one we created in the section “Creating Search Managed Properties for Content” earlier in this chapter). The ManagedPropertyMapping tag is a comma-separated list of managed property names and the properties in the UI to which they are mapped (see Listing 9-8). The UI properties can be mapped to multiple managed properties, other than the ones specified using the Property Mappings section of the Content Search web part tool pane.
For example, within the ManagedPropertyMapping tag, both PictureURL and PictureThumbnailURL are mapped to Image URL.
'Image URL': 'PictureURL;PictureThumbnailURL', 'Line 1':'Title', 'Line 1 Link':'Path',...
For our custom Item display template, we need to add two managed properties (see Listing 9-8).
Listing 9-8. Add Managed Properties to the Display Template and Map the Property to a Property in the UI
<mso:ManagedPropertyMapping msdt:dt="string">
'LastModifiedTime':'LastModifiedTime',
'Specter Property Type'{Specter Property Type}:'SpecterPropertyType',
'Picture URL'{Picture URL}:'PublishingImage;PictureURL;PictureThumbnailURL',
'Link URL'{Link URL}:'Path',
'Line 1'{Line 1}:'Title',
'Line 2'{Line 2}:'Description',
'SecondaryFileExtension',
'ContentTypeId'
</mso:ManagedPropertyMapping>>
Adding Inline JavaScript
As mentioned earlier all the HTML and JavaScript code we want to render on the page must be included inside of the first <div> tag.
Continue with the Item_LargePicture.html page, below the first <div> tag, and add the inline JavaScript code in Listing 9-9 to get data for each item.
Listing 9-9. Inline JavaScript Added to the Custom Item Display Template to Get Data for Each Result Item
var encodedId = $htmlEncode(ctx.ClientControl.get_nextUniqueId() + "_largePicture_Specter_");
var linkURL = $getItemValue(ctx, "Link URL");
linkURL.overrideValueRenderer($urlHtmlEncode);
var line1 = $getItemValue(ctx, "Line 1");
var line2 = $getItemValue(ctx, "Line 2");
var pictureURL = $getItemValue(ctx, "Picture URL");
var pictureId = encodedId + "picture";
var pictureMarkup = Srch.ContentBySearch.getPictureMarkup(pictureURL, 468, 220,
ctx.CurrentItem, "cbs-largePictureImg", line1, pictureId);
var specterPropertyType = $getItemValue(ctx, "SpecterPropertyType");
var lastModifiedTime = $getItemValue(ctx, "LastModifiedTime");
var m_names = new Array("Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec");
var d = new Date(lastModifiedTime);
var date = d.getDate();
var d_month = d.getMonth();
var month = m_names[d_month];
For the purpose of demonstration, let’s break the inline JavaScript in our solution into three sections.
var encodedId = $htmlEncode(ctx.ClientControl.get_nextUniqueId() + "_largePicture_Specter_");
var linkURL = $getItemValue(ctx, "Link URL");
linkURL.overrideValueRenderer($urlHtmlEncode);
var line1 = $getItemValue(ctx, "Line 1");
var line2 = $getItemValue(ctx, "Line 2");
var pictureURL = $getItemValue(ctx, "Picture URL");
var pictureId = encodedId + "picture";
The pictureMarkup value is derived from the getPictureMarkup function, which retrieves the HTML markup of an image with the image’s URL and ID
var pictureMarkup = Srch.ContentBySearch.getPictureMarkup(pictureURL, 468, 220,
ctx.CurrentItem, "cbs-largePictureImg", line1, pictureId);
var specterPropertyType = $getItemValue(ctx, "SpecterPropertyType");
var lastModifiedTime = $getItemValue(ctx, "LastModifiedTime");
var m_names = new Array("Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec");
var d = new Date(lastModifiedTime);
var date = d.getDate();
var d_month = d.getMonth();
var month = m_names[d_month];
Adding HTML Markup
Now we are ready to add some HTML markup to the custom item display template file to display data for each item. Scroll down the Item template HTML file to find the original HTML we want to remove (see Listing 9-10).
Listing 9-10. Out-of-the-Box HTML Markup in the Item_LargePicture HTML File
<div class="cbs-largePictureContainer" id="_#= containerId =#_"
data-displaytemplate="ItemLargePicture">
<div class="cbs-largePictureImageContainer" id="_#= pictureContainerId =#_">
<a class="cbs-pictureImgLink" href="_#= linkURL =#_"
title="_#= $htmlEncode(line1) =#_" id="_#= pictureLinkId =#_">
_#= pictureMarkup =#_
</a>
</div>
<div class="cbs-largePictureDataOverlay" id="_#= dataContainerOverlayId =#_"></div>
<div class="cbs-largePictureDataContainer" id="_#= dataContainerId =#_">
<a class="cbs-largePictureLine1Link" href="_#= linkURL =#_"
title="_#= $htmlEncode(line1) =#_" id="_#= line1LinkId =#_">
<h2 class="cbs-largePictureLine1 ms-noWrap" id="_#= line1Id =#_">
_#= line1 =#_
</h2>
</a>
<div class="cbs-largePictureLine2 ms-noWrap" title="_#= $htmlEncode(line2) =#_"
id="_#= line2Id =#_" > _#= line2 =#_</div>
</div>
</div>
Before we remove it, however, let’s review the out-of-the-box HTML. Note the out-of-the-box template uses the ID from the search result as unique identifiers for some of the HTML tags. It displays the Title and Description managed properties for each result. It also shows pictureMarkup, which is a variable that was created from inline JavaScript shown previously that gets the HTML markup of the image for each search result. The inline JavaScript lives right above this code as shown in the previous section.
Let’s first replace this HTML markup with the HTML markup in Listing 9-11 to render each search result with the responsive design we implemented in the previous section. The HTML in Listing 9-11 generates the HTML markup for the Item display template while referencing the custom CSS for look and feel.
Listing 9-11. New HTML Markup for the New Item Display Template
<span class="_#= specterPropertyType=#_">
<a href="_#= linkURL =#_" class="thumb">
_#= pictureMarkup =#_
<div class="date">
<div class="d">_#= date=#_</div>
<div class="m">_#= month=#_</div>
</div>
</a>
<div class="caption">Property Type: _#= specterPropertyType=#_</div>
</span>
The end product of this HTML markup is Figure 9-56. As you can see, the display template displays an image, the last modified date, and the property type of a Floor Plan item.
Figure 9-56. End product of the HTML markup for the custom Item display template
Let’s discuss each part of the HTML markup in detail.
Recall from earlier that we talked about each Item display template renders an empty <li> tag, and under the <li> tag is where the content for each item goes. Inside of the Item display template, you will not see the actual <li> tag because it is generated for each item by SharePoint during runtime. Hence we cannot add any style, ID, or CSS class to this <li>. Recall from the Style for Each Item section, we created the CSS style for an <li> tag under a <ul> tag that has a feature class. Because we have already added the feature class to the <ul> tag, the <li> generated by SharePoint will automatically pick up the style we have created under the .feature li CSS code block demonstrated in Listing 9-2. As a result, each item will now be displayed in a three-column table.
For each search result, we want to display an image of the floor plan. pictureMarkup is a variable that was created from inline JavaScript that gets the HTML markup of the image for each search result (as described in the previous section).
For each search result, we want to show the date the floor plan was modified. Both "date" and "month" are variables created from inline JavaScript that gets the date and month values from the LastModified managed property. The date and month class are added to style each result item with a circle for the date as specified in a CSS code block (Listing 9-5) in the style.css file we have in the Master Page Gallery.
For each search result, we want to show the property type of each floor plan. specterPropertyType is a variable created from inline JavaScript that gets the value from the SpecterPropertyType managed property (as described in the previous section). The caption class is added to style each result item with a circle for the date as specified in a CSS code block (Listing 9-4) in the style.css file we have in the Master Page Gallery.
As you can see, we are displaying the values of many managed properties throughout the template. We have plugged these values using the _#= and =#_ tags into the appropriate DIV or SPAN tags for formatting.
Integrating Search Results with the Custom Item Display Template
We have made all the necessary changes for the custom Item display template, Item_LargePicture_Specter.html, to render each result based on the Specter design. For other scenarios, if you have a different look and feel for each item, you would need to add specific CSS and HTML markup in the custom Item display template HTML file.
Figure 9-57. Properties to set when uploading a custom Item display template file to the Master Page Gallery
Figure 9-58. Change Control display template to List Specter and Item display template to Specter Large Picture
Note To get the same branding as the Specter design, make sure you are using the same Specter Group master page from Chapter 5 because we need to reference styles added to the style.css file, which is included in the Specter Group master page.
Once the page is saved, the result page should look like Figure 9-59.
Figure 9-59. Result Floor Plans page after adding custom Control and custom Item display templates
Limitations of Display Templates
Earlier, we learned that each Item display template generates its own <li> tag during runtime. This means we cannot add ID, CSS class, or styles to the <li> tag because it does not exist in the display template at design time. When designing an HTML page, there are times when it requires us to add a CSS class to the <li> tag for each item; for example, when dealing with jQuery plug-ins, such as Isotope to provide dynamic filtering features to a list. In the case of Isotope, to make the filtering feature work, we need to add a CSS class to a <ul> tag and its immediate children <li> tags. Because we are working with display templates in SharePoint, when SharePoint renders each item with a given Item display template, an <li> tag will be automatically generated. Hence, when designing the display template, we cannot configure the <li> tag with any CSS class or ID, as required by the Isotope plug-in. As a result, the filtering feature provided by the Isotope jQuery plug-in does not work in display templates in SharePoint without changing the plug-in’s code.
Query Rules, Result Types, and Display Templates
In the previous section, we looked at how to create a content rollup solution using custom display templates and the cross-site publishing feature. Now we are going to look at how floor plans are rendered in search. We look at how we can fine-tune search queries and customize the display of results when users search for floor plans. SharePoint 2013 provides new features like query rules, result types, and display templates to allow better tuning and better presentation of search results based on the intent of the user’s query.
For the Specter Group Floor Plans scenario, we are going to create a query rule and a result type for floor plans, such that when users search for the keyword “floor plans,” the following things happen:
For an example of how to configure query rules and result types, refer to the sections “Create a Query Rule to add a Summer Promotion for Beachfront Properties” and “Adding a Result Type for Floor Plans to Use Best Bet Item Display Templates,” respectively.
Query Rules
In SharePoint 2010, one query has one set of results. In SharePoint 2013, we are able to fine-tune search results based on the intent of the user’s query. When users enter a query, we help them find what they are really looking for by fine-tuning the query and adding additional information to offer results that we think the users are looking for. We can create query rules to trigger multiple queries and multiple results sets for a user’s search requests. All matching query rules can generate results. The query orchestration engine retrieves all the different sets of results and renders them to the user. The results are then rendered in a specific user interface based on their result types and the display templates associated with it. For more information on result types and associated display templates, refer to the section “Result Types” later in this chapter.
When creating a new query rule, there are three components to configure:
Query rules can be created at various levels, in the Search Service application from Central Admin or at the site collection level. They are inherited by default, such that query rules created in the Search Service application are inherited by all the site collections and query rules created at the site collection level are inherited by all sites within the site collection. They can also be deactivated at a level to ensure the rule is never applied for queries submitted at that level.
Note If multiple query rules are active and more than one rule can be matched for a given query, then the rules will be executed in no specific order because there is no prescribed order for execution. To ensure query rules are ranked for orders of execution, a custom group needs to be created to organize the query rules. Refer to http://sprwd.com/4czkg54 for more information.
Conditions allow us to define the criterion under which the query rule should apply. Each query rule can have multiple conditions. If no condition is specified, the query rule is triggered every time. If multiple conditions are specified, as long as one of the conditions is matched, then the query rule will be invoked. There are six types of conditions to choose from when creating a query rule:
Note For more information on all the query rule conditions, refer to http://sprwd.com/sqs8jgt.
For the Specter Group Floor Plans scenario, we are going to configure our query rule for Floor Plans with the condition to match keyword “Floor plans.” Refer to the section “Creating a Query Rule to Add a Summer Promotion for Beachfront Properties” later in this chapter for more detail.
Query Rule Actions
Next, we need to configure actions to specify what happens when the query rule is applied. We can add multiple actions for each query rule. There are three options for actions:
Caution Expanding the original query increases the time needed to execute the search query because additional queries are executed and additional result sets are returned. Be cautious when designing a query, as it might return too many search results, such that the query gets timed out or takes a really long time to finish.
Note When ranking a result block, the ranking applies to the entire block, not to individual items within the block. Every individual query made by every individual user is logged, as well as the user’s click-through choices. As items in a result block are clicked, the entire result block shows up higher in the search results. In time, the entire result block can start to percolate up to the top of the search results if users continue to select items in it.
For the Specter Group Floor Plans scenario, we are going to configure our query rule for Floor Plans with an action to add promoted results for a few beachfront properties.
The publishing options for a query rule determine when the rule can be used. By default, a rule is active until it is deactivated. We can also configure a rule to be active during a certain time. A good application of this is when a rule is set up for commerce scenarios. For example, we can set up a rule to promote certain products to the top for sale during a particular period of time, such as the holiday period.
In the Specter Group’s scenario, we want to show beachfront properties in the summer period. Refer to the section “Creating a Query Rule to Add a Summer Promotion for Beachfront Properties” later in this chapter for more detail.
We have created query rules to help us get the results. Now let’s see how we can display the results. SharePoint 2013 introduces a new framework, result types, for presenting search results to end users. Each result type has its own display template, making different types of results look distinct from each other and surfacing properties that are most relevant to that type of results. We can create result types to invoke display templates based on a set of rules. Each result type has the following elements.
By default, SharePoint offers several out-of-the-box result types. For example:
For the Specter Group Floor Plans scenario, we create a custom result type for floor plans to point the Floor Plans result type to the Best Bet Item display template. Now when users issue a query, each result is evaluated against the result type rules. If the item is a result from the Floor Plan result source, the result item will be displayed using the Best Bet Item display template to distinguish it from all other results in the list. Otherwise, the result item will be displayed using another default template.
Creating a Query Rule to Add a Summer Promotion for Beachfront Properties
For the Specter Group search scenario, when users search for “floor plans,” we want to create a query rule to promote beachfront properties during the summer season. Because our query rules are used to display results to site visitors of the Specter Group public-facing site, we create the query rule at the site level for the public-facing site. Figure 9-60 shows the default search results page when a user enters “floor plans.” As you can see, results of all types from the search index are interleaved based on their ranking. Each result has a result type, which determines how the item is rendered in the Search Results web part.
Figure 9-60. Search results with out-of-the-box configurations
Let’s create a query rule to promote beachfront properties during the summer promotion season.
Figure 9-61. Create a new query rule for a result source
Figure 9-62. Add a condition to a query rule
Figure 9-63. Add a promoted result as the query rule’s action
Figure 9-64. Configure Actions for a query rule
Figure 9-65. Configure Publishing for a query rule to specify when the rule is active
Figure 9-66. Summary of the new query rule
Figure 9-67. Search results page with promoted results after the new query rule is triggered
Adding a Result Type for Floor Plans to Use Best Bet Item Display Templates
Our next scenario is to create a result type for Floor Plans so that when users search for floor plans, they will be able to quickly spot the results in the Floor Plans result source from all other results in the list.
Figure 9-68. Create a new result type for all items in a result source
Figure 9-69. Configure the new result type to use the Best Bet Item display template
Figure 9-70. Summary of the new result type
Figure 9-71. Search results page with promoted results at the top and best bet rendering of all floor plan items after the new query rule is triggered and the new result type is added
Now we have the promoted results at the top of the page and each floor plan result is rendered using the Best Bet Item display template so that they are distinguished from the rest of the results in the list.
Summary
With the new publishing and search features in SharePoint 2013, we are able to use the power of search to surface dynamic web content on sites. In this chapter, we learned how to create beautiful search experiences using the new user experience framework in SharePoint 2013 by using the new Content Search web part combined with HTML, JavaScript, CSS, query rules, result types, and display templates. We created a content rollup solution by creating custom display templates for SharePoint’s Content Search web part. Then, we look at how to fine-tune search queries and customize the display of results in a search by using query rules and result types to improve the search experience.