Category Archives: Uncategorized

JSLink and Display Templates Part 1 – Overview, URL Tokens and Applying JSLink to objects

This is the first in a 4 part series about JSLink where I intend to go through all the ins and outs of using Display Templates to customise list rendering.

This first section really covers off the basics. It doesn’t contain any real sample code about the Display Templates (that is in Parts 2, 3 and 4) but does explain what JSLink is and how you can apply it to different objects.

What is “JSLink” exactly?
I think there has been a fair amount of confusion over what the terminology “JSLink” actually means. I’ve commonly seen it referred to as the technology which allows you to customising field and list rendering but that is really the Display Template functionality.

In a nut-shell JSLink simply means “link to my JavaScript file”

This is basically a URL to a JavaScript file. It doesn’t really matter where this file is (it could just as easily be in a document library or the Layouts folder). There are a vast number of objects you can attach JSLink references to but the ones we are really interested are:

  • Site Columns
  • Content Types
  • List Views
  • List Forms (e.g. New / Edit / Display forms)
  • List View Web Parts
  • List Form Web Parts

This gives us the full battery of places that we need in order to get our JavaScript in the right place at the right time, some of which are clearly desirable for different reasons.

JSLink URLs and Tokens
When you are constructing your JSLink URL there are a number of tokens you can take advantage of:

  • ~site – reference to the current SharePoint site (or “Web”)
  • ~sitecollection – reference to the current SharePoint site collection (or “Site”)
  • ~layouts – version specific reference to the web application Layouts folder (so it will automatically swap out /_layouts/14 or /_layouts/15 for you)
  • ~sitecollectionlayouts – reference to the layouts folder in the current site collection (e.g. /sites/team/_layouts/15)
  • ~sitelayouts – reference to the layouts folder in the current site (e.g. /sites/teams/subsite/_layouts/15)

This allows you to easily make sure that your JSLink files are targeted correctly (whether you are provisioning them to a specific library, or want to make sure your _layouts URL is constructed appropriately).

You can also apply more than one JSLink reference at a time by separating each reference with the pipe | symbol. So if you wanted to include two custom JSLink files on a field you might use the following attribute:

JSLink=~sitecollectionlayouts/MJH/JSLink1.js|~sitecollectionlayouts/MJH/JSLink2.js

Applying your JSLink References
You have a whole range of different options for applying your JSLink to the different objects, and this will largely depend on where you want your customisations to be applied.

If you are creating a new custom field type then you would implement it at the Site Column level. If you want to do something specific such as cascading drop-downs then you might want to do that at the Content Type or List (form) level.

If you are doing a one-off demo in an environment where you don’t have a high level of permissions then you can apply the JSLink references to the List View or Form Web Parts (although appreciate that this obviously doesn’t scale particularly well as you would have to manually apply it to each web part).

You can apply them using XML as part of your Site Column, Content Type or List View definitions. Each of these contains a JSLink attribute which you can use to populate a URL

JSLink=~sitecollectionlayouts/MJH/JSLink1.js

You can also apply them to the above, as well as list forms using Server Side Code (I’m not sure if there is a client side object model equivalent).

SPList list = web.Lists.TryGetList(“My List”);
if (list != null)
{  SPForm editForm = list.Forms[PAGETYPE.PAGE_EDITFORM];
  editForm.JSLink = “~sitecollectionlayouts/MJH/JSLink1.js”;
}

You can even do this in PowerShell if you are properly hardcore 🙂

$web = Get-SPWeb https://teamsite.mjh
$field = $web.Fields[“MJHSampleField”]
$field.JSLink = “~layouts/MJH/JSLink1.js”
$field.Update($true)

And finally you can set this in the List View Web Part or List Form Web Part using the web part properties:

Add your JSLink reference to Web Part properties

There is also a final option where it seems you can create re-usable templates by uploading your templates into the Master Page Gallery so they appear as new “View Types” when users are creating new Views for their lists, but more about that in Part 5!

So that covers all of the basics about what JSLink actually is, how the URLs are constructed and how you can apply them. In the next few parts we will be looking at the sample code and walking through some real-world examples of how you can use JSLink along with Display Templates to implement custom field and view rendering.

Next: Part 2 – Changing how individual fields display

Customising the Content Search Web Part – Part 2 – Custom Display Templates with JavaScript

This is the second post in a series I will be writing on the Content by Search Web Part (aka CSWP).

  1. What you get in the box
  2. Custom Display Templates with JavaScript (this post)
  3. Going Old Skool with XSLT
  4. Packaging & Deployment in Visual Studio

So if you’ve read Part 1 (what you get in the box) then you should have a pretty good idea of what the CSWP can do by now and what Display Templates and Property Mappings are (if you don’t then go back and read Part 1 .. I won’t be explaining them again).

So now we move onto the brave new world of building and defining your own custom Display Templates. The first thing you need to know is that Display Templates are stored in the Master Page Gallery (No, I don’t know why) specifically in a sub-folder called “Display Templates”.

Item Templates in the Master Page & Page Layouts Gallery

In here you will find two types of file:

  • HTML files – these are the actual Display Templates (and what you will copy/create when you create your own custom template)
  • JS files – These are the “compiled” JavaScript files which are automagically created by SharePoint when you add / modify one of the HTML templates

Display Template basics – Using JavaScript
The out of the box display template files actually include some pretty useful comments which tell you how this works, but basically you have two “tokens” that you need to use:

To Write JavaScript explicitly you need to use HTML comments with #_ and _# at each end. This tells SharePoint that it needs to take whatever is inside these tokens and “compile” it into JavaScript in the finished file. For example:

<!–#_ var myString = ‘Hello World’; _#–>

This allows you to write pretty much any JavaScript that you like. You can use this JavaScript to retrieve values from your Property Mappings as follows:

<!–#_ var linkURL = $getItemValue(ctx, “Link URL”); _#–>

In the above example “Link URL” is the name of the Property Mapping. If you then want to use those variables in your HTML you simply wrap then in =#_ and _#= tokens. For example:

<a href=”_#= linkURL =#_”>
  <span> _#= myString =#_</span>
</a>

It really is that simple!

But before we look at actually creating a new Display Template, what we really need is a problem to solve (I find it helps to focus the mind) ..

A suitable problem – Pictures, Publishing Pages and Image Renditions, oh my!
One of the great new features in SharePoint 2013 is “Image Renditions” (explained in great detail by Waldek Mastykarz). The cool thing is that if you have registered an Image Rendition with a desired width / height then you can include those as URL attributes and SharePoint will resize the image server side! This is a fantastic feature, it (drastically) reduces image sizes and ensures that the output is consistently rendered.

The out of the box display templates will automatically use these Image Renditions (the “Large Picture” template for example will ask SharePoint for an image which is 468×220, which matches one of the out of the box image renditions).

However when you try to use Image Renditions with the CSWP then you get some pretty odd results. To demonstrate this I have uploaded 4 photos from one of my holidays a few years back. I then created a Publishing Page for each photo and selected different Image Renditions for each page.

I then displayed then using the CSWP using the “Large Picture” item template and here are the results:

 

CSWP displaying the actual photos in the Asset Library

 

CSWP displaying the Publishing Pages (and pulling the associated image)

As you can see the second one looks a bit screwy as all of the images are different sizes. So what on earth is happening? Well, on checking the URL for one of the images which is being returned I can see that the image URL is correctly picking up the including the Rendition ID that I picked on my publishing page.

..photos/DSC_1002.JPG?RENDITIONID=1&width=468&height=220

This is bad, because when SharePoint renders an image it will first look for the RenditionID and if it finds one it will ignore the width and height attributes!

The solution – Custom Display Template
So in order to fix this we need to create ourselves a custom Display Template so we can strip out that RenditionID attribute using JavaScript so the images served by SharePoint come out in the correct size.

So first off, I went and downloaded a copy of the Item_LargePicture.html file (which I used as my starting point) and renamed it (to “Item_LargePictureFixed.html”).

The next thing to do is to rename the <title> attribute in the file. This is what gets used in SharePoint to identify the template in the CSWP web part properties.

<title>Large Picture (FIXED)</title>

Now, I also wanted to add some more detail to my display template as just showing the title wasn’t that great (bringing back the publishing date and author for the page would be cool) .. and it also allows me to demonstrate how the Property Mappings work.

So the next thing is to look for an XML element near the top of the file called mso:ManagedPropertyMapping. This contains all of the Property Mappings that the CSWP will pick up when your template is in use.

When you define Property Mappings you can also define the search properties it should look for and the format you need to use is:

<Mapping Name>:<Search Property1>;<SearchProperty2>

Each mapping is separated by a comma (,) so my custom mappings were

  • Image Title (mapped to “Title”)
  • Image Date (mapped to “ImageDateCreated” and “LastModifiedTime”)
  • File Author (mapped to “Author”)

‘Image Title’:’Title’,’Image Date’:’ImageDateCreated;LastModifiedTime’,’File Author’:’Author’

Don’t forget that our properties map to Search Properties .. so if the field isn’t being indexed by Search then you won’t be able to use it!

Once we had our mappings in place we can pull it all into variables using JavaScript. This includes a (slightly nasty) sub-string function to pull out any URL attributes for the Image URL

<!–#_

var pictureURL = $getItemValue(ctx, “Picture URL”);

// get the picture URL as a string
var cleanPictureURL = pictureURL.toString();

// check if it contains any query string arguments
if(cleanPictureURL .indexOf(“?”) != -1)
{
// if it does, then strip them out
var renditionIndex = cleanPictureURL .indexOf(“?”);
cleanPictureURL = cleanPictureURL .substring(0, renditionIndex);
}

// add the width/height attributes back in for the image renditions
cleanPictureURL = cleanPictureURL + “?width=468&height=220”;
// get our three other property values
var imageTitle = $getItemValue(ctx, “Image Title”);
var imageDate = $getItemValue(ctx, “Image Date”);
var fileAuthor = $getItemValue(ctx, “File Author”);

_#–>

Once that was done all we needed was to make sure our variables were used in the right parts of the HTML. I then uploaded the HTML file (which effectively installs the new Display Template) and wired it up in the Web Part.

New Display Template with new Property Mappings being displayed
New “fixed” Display Template with correct sized images, and new property mappings being displayed

If you want to take a closer look then you can download the example HTML file here:
https://sdrv.ms/172o9rM

So that is it for CSWP Display Templates .. in part three we will look at going old school with XSLT rendering.

Customising the Content Search Web Part – Part 1 – What you get in the box

This is the first post in a series I will be writing on the Content by Search Web Part (aka CSWP).
  1. What you get in the box (this post)
  2. Custom Display Templates with JavaScript
  3. Going Old Skool with XSLT
  4. Packaging & Deployment in Visual Studio

Search is quick, Search is vast, Search is better .. Well where do I start? SharePoint 2013 is all about Search. It has a completely rebuilt search engine which incorporates a lot of the awesome power that Microsoft gained from FAST over the years.

I’ve seen, a lot of SharePoint projects over the years which have been based heavily around Search, typically using custom developed web parts based on the Search Core Results web part. Because the core search web parts used XSLT for their rendering we could totally customise the interface and output. They included an out of the box “paging” capability and through the query syntax you could build quite sophisticated queries.

Search gives you the ability to pull immensely vast amounts of information from your sites (or other sites, public websites, file shares, even Exchange!) and return them in an extremely quick fashion. In terms of querying and returning information it is formidably fast the only real  downside being the time it takes for search to actually index your content (which even on a well optimised farm was only going to be around 15 minutes at best). SharePoint 2013 introduces Continuous Crawls which basically allows content to be indexed almost immediately (with typically around a 30 second delay).

Even without those indexing issues though the main problem with these search based approaches is that they tended to have very unsophisticated editing capabilities for the people building the pages. You needed to have a damned good knowledge of the Search Keyword Query Syntax and this was just yet another hurdle for editors who are just trying to put pages together

Enter the Content Search Web Part!
The SharePoint 2013 solution to this is the Content by Search Web Part (CSWP) which is basically designed to be a replacement for the trusty Content by Query Web Part (CQWP) which we have been used to using in most of our projects in SharePoint 2007 and 2010.

This includes a number of outstanding features:

  1. Very advanced “query editor” which use a separate pop-up dialog. This allows you to define very complex search queries to bring back almost any granularity of information
  2. Query shortcuts are also built into the query editor, so you can easily tell the web part to only return content from the current site, or site collection, or just return documents / pictures, or a whole range of other content.
  3. A range of different Display Templates are provided allowing you to switch between different “styles” (including paging!). These templates are fully extensible and adding your own custom templates will be covered in Part 2 of our series.
  4. The values being shown in the output can be controlled and modified using “Property Mappings” (which is covered later in this post).
  5. User Profile Tokens allow values in the current user’s profile to be swapped out “on the fly”. This is massive! This alone makes the CSWP worthwhile (e.g. pull back all news articles tagged with the user’s department?)

I could go on because this web part is immense and in every way an improvement. The performance is lightning quick and if you aren’t using it then you really need to consider why not!

The “Build Your Query” wizard
The first thing we will look at is the query editor. This is a fantastic new wizard interface which you can access from the Web Part properties.

Change Query pops up the Build Your Query pop-up

This allows at first a basic mode which allows you to select from various prebuilt result sources. This in itself probably allows you to meet 90% of your search requirements.

In Basic Mode, you can pick from result sources, restrict by site / URL and access basic selections

The basic mode also allows access to an easy “Restrict by app” which effectively means “restrict by URL” but allows you to easily pick “Current Site” and “Current Site Collection”.

In Advanced mode you can construct pretty much any query you want using the SharePoint 2013 Keyword Query Language (KQL) Syntax.

Advanced Mode allows extensive custom KQL queries, such as the above which returns people who have a profile picture and their “About Me” section contains the word “SharePoint”

You can even refine this further using the “Refinement” panel which allows you to cherry pick different values in a very similar fashion to the refinement panels you will have seen in SharePoint search results pages.

You can cherry pick refiners to trim down the results, much as you would if you were viewing a Search results page.

You also have an ever-present “Test Results” panel on the right hand side which allows you to view what you might get in your results given the current settings…

One other new addition is a new user token which allows you to include properties from the current user in your search queries dynamically (clearly great minds think alike… ).

Adding the current user puts {User.Name} in the query

Using the “Name of the user who runs the query” token places a construct of {User.Name} which will basically replace that with the name of the current user each time the page is accessed. I have found however that you can swap this out with other user profile properties as well (such as {User.Department} or {User.JobTitle} .. however not all of them seem to work, some experimentation is required!).

This provides an amazing opportunity to create truly personalised feeds of information where the results are relevant to the current user, based on whatever they have selected in their profile.

.. All in all, this is a fantastic improvement over any of the previous query editing interfaces in SharePoint, and allows you to configure in some cases extremely complex queries.

Switching Display Templates and Configuring Property Mappings

Note – in Part 2 of this series we will look at building our own custom Templates, but for now we will be looking at how we can customise the look using the out of the box templates.

Now this should be familiar to anyone who is used to working with the Content by Query Web Part.

First up lets talk about the display templates. A bunch of these come out of the box and basically control the look and feel of the contents of the web part. There are two types which you can select:

  • Control Templates – These determine the rendering container or wrapper of the contents
  • Item Templates – These determine the rendering of each item which is returned in the results
Display Templates are picked from the Web Part Properties

These are all JavaScript based, so you might see some delays before it renders, but they are in my experience both fast and adaptable.

The specific templates you get are:

Control Templates

  • List
  • List with Paging
  • Slideshow

Item Templates

  • Diagnostic
  • Large Picture
  • Picture on Left, 3 Lines on right
  • Picture on Left, 3 Lines on bottom
  • Recommended Items: Picture on Left, 3 Lines on right
  • Two Lines
  • Video

Most of these should be pretty self-explanatory but some of them deserve special mention.

The List with paging control template adds next/previous paging controls (implemented using Async JavaScript) while the Slideshow control template provides a javascript based fade-in / fade-out animation.

The Video item template actually adds an HTML5 video object but probably the most useful one is “Diagnostic”. When picked this displays detailed information about your Property Mappings which is what allows you to really understand what information your Content by Search Web Part is displaying ..

Property Mappings
So .. what are these property mappings and what do they do?

Well .. you remember some of the difficulty in trying to map fields to a Content by Query web part (and passing them back to the back-end XSLT)… well the Content by Search Web Part uses Property Mappings which map to Display Templates (which are JavaScript powered) .. and it works incredibly well!

Basically the Item display template you pick will have a number of properties which need to be mapped, so in the example below I have picked the Item Template “Picture on Left, 3 Lines on right”.

As a result there are 5 properties which need mapping:

  • Picture URL (i.e. the image to be displayed)
  • Link URL (i.e. where you should go when you click on the item)
  • Line 1 – I have chosen Title
  • Line 2 – I have chosen Description
  • Line 3 – I have chosen LastModifiedTime
Property Mappings allow you to control what appears in what parts of the chosen template

The templates are generally intelligent enough to know if the property doesn’t have any values, or if you haven’t actually mapped it to anything.

So this is yet another level of customisation you can apply, and the drop-down menu on each mapping allows you to cherry pick from the properties which have been indexed and mapped in the current search service.

The really great thing here is that the mappings will change depending on the template (and when you get to building your own, you can specify your own mappings). This is where the Diagnostic item template really comes into its own, as it allows you to pull in 9 fields of your choice and it displays detailed information from the results, showing you what the value is and what the mapping is for each item.

Well that is all for now so hope you realise like I do how powerful the Content by Search Web Part can truly be.

Next in the Series : Custom Display Templates with JavaScript

Recent Entries »