Spca2014 js link and display templates hatch

22

Transcript of Spca2014 js link and display templates hatch

Page 1: Spca2014 js link and display templates hatch
Page 2: Spca2014 js link and display templates hatch

Martin HatchSharePoint Practice Lead @ Ballard Chalmers, UK

Advanced List Rendering with JSLink and Display Templates

@MartinHatch

https://martinhatch.com

[email protected]

Slide Deck: http://mhat.ch/SPConnect14Code: http://mhat.ch/JSLinkCode

Page 3: Spca2014 js link and display templates hatch

• Custom Fields• Display Forms and Views

• New and Edit Forms

• Validation

• Advanced Techniques (SOD / AJAX / JavaScript CSOM)

• Custom Views• Headers & Footers

• Item Templates

• Gotchas (Quick Edit / Paging)

• Multiple Language Support (RESX files in JavaScript!)

• Leveraging JSLink

• Deploying with Visual Studio

Agenda

Page 4: Spca2014 js link and display templates hatch

• Just some JavaScript which needs to be loaded on the page (the Script Editor Web Part is a nice way to do simple testing)

• It essentially just returns some HTML as a string value

• List Display Templates can be targeted to a specific List Template Type (e.g. 100 = Custom List, 101 = Document Library)

• Display Templates execute VERY early in the page lifecycle, so you’ll have to be creative if you want to leverage CSOM or AJAX

Display Templates 101

Page 5: Spca2014 js link and display templates hatch

var fieldOverride = {};

fieldOverride.Templates = {};

fieldOverride.Templates.Fields = {

“InternalFieldName”: {

“NewForm”: myNewForm,

“EditForm”: myEditForm,

“DisplayForm”:myDisplayMethod,

“View”: myViewMethod

}

};

// Optional: Restrict this template the “Custom List” template

fieldOverride.ListTemplateType = 100;

// register our field override with SharePoint

SPClientTemplates.TemplateManager.RegisterTemplateOverrides(fieldOverride);

A basic Display Template

Rinse-and-Repeat to override multiple fields

This line tells SharePoint about our template

Page 6: Spca2014 js link and display templates hatch

• Each render method receives a “context” object which allows you to pull out some key information:

• CurrentFieldValue

• CurrentFieldSchema

• CurrentItem*

* CurrentItem also contains built-in variables for each field that the item has, so you can use for example “CurrentItem.Title”

Custom Fields: Views and Display Forms

Page 7: Spca2014 js link and display templates hatch

function RenderFieldValue(ctx) {

// place in a div to make sure the description field (if present)

// wraps to the next line

return "<div>" + ctx.CurrentFieldValue + "</div>";

};

• End of the day it is just a method which returns some HTML

• Be careful of Taxonomy / Lookup fields as it will include the raw value and not “clean” text (e.g. “1#;Lookup Item A”)

Custom Fields: Basic Display Form

Page 8: Spca2014 js link and display templates hatch

DEMOCustom Fields: Views and Display Forms

..............................

Page 9: Spca2014 js link and display templates hatch

• These are the same as the Display Form, except we now need to provide SharePoint with the field value on save

• We can do this using a RegisterCallbacks method, passing it the method which will return the field value (as a string).

• How you retrieve and format the value is up to you, but don’t forget to read in the current item value when the edit form loads!

• Be aware that complex data types (Lookups / Taxonomy Fields) will expect the data in a specific format!

Custom Fields: New and Edit Forms

Page 10: Spca2014 js link and display templates hatch

• You can register Validators for ANY field (even if you aren’t providing a display template for rendering)

• Standard validation (e.g. “Mandatory / Required Field”) will be implemented automatically, so you only need to add your own.

• When you register your validator you need to provide 3 things:• An object which contains a “Validate” method (returning true or false)

• A callback method for when the field does not validate.

• The field you want to bind the validator to.

Custom Fields: Validating User Input

Page 11: Spca2014 js link and display templates hatch

DEMOCustom Fields: Editing and Validating

..............................

Page 12: Spca2014 js link and display templates hatch

• The “Display Template” rendering occurs very early in the page load cycle, which has a few knock-on affects:

• The JavaScript CSOM doesn’t work as “ClientContext” is null

• Script on Demand methods “RegisterSod” and “LoadSodByKey” need to be called before your override template or it won’t work

• Attempting to slow this process down will break your template:• $(“document”).ready(function() { });

• ExecuteOrDelayUntilScriptLoaded(function() { }, “scriptkey”);

Its all about the timing …

Page 13: Spca2014 js link and display templates hatch

• Simple Rules:• Instead of CSOM, use an AJAX request with the REST API which has no

“page state” dependencies

• Instead of using “RegisterScript” roll your own

• Return the bare minimum HTML

• Create a separate async function to do all your processing (which you can fire off once the page is finished rendering)

… working around your limitations

Page 14: Spca2014 js link and display templates hatch

• SharePoint contains a Script RESX Handler which will automatically generate a JavaScript object containing the resource strings for the current UI culture

\_layouts\15\ScriptResx.ashx

?name=MyResourcefile

&culture=en-US

• _spPageContextInfo.currentUICultureName is generated by SharePoint automatically generates

Multiple Language Support

Page 15: Spca2014 js link and display templates hatch

• “resheader” attribute needs to be added manually (the SharePoint ones already have this value)

<resheader name="classFullName">

<value>My Namespace</value>

</resheader>

• Resource file must be in the \15\Resources folder.

• This technique does NOT work in Office 365. As an alternative, store a list of string variables in a JS files using the UI Culture as the filename and dynamically load them

RESX file .. Some assembly required

Page 16: Spca2014 js link and display templates hatch

DEMOJavaScript Multi-Language Support

..............................

Page 17: Spca2014 js link and display templates hatch

JSLink – The magic plumbing

• A mechanism which allows you to “attach” JavaScript to different SharePoint elements

• Any JavaScript specified is automatically added to the page when that “element” is rendered

• Tokens available to create SharePoint contextual URLs:• ~layouts

• ~sitecollectionlayouts

• ~sitecollection

• ~site

Page 18: Spca2014 js link and display templates hatch

JSLink

• You can include multiple JavaScript files by separating them with the “pipe” | symbol. These will be loaded left-to-right

• ~layouts/firstFile.js | ~layouts/secondFile.js

• SharePoint will automatically ensure that the same file is not loaded in twice (so you don’t need to worry about duplication!)

Page 19: Spca2014 js link and display templates hatch

JSLink – The good and the .. challenges

• You can leverage JSLink from different places, but these all have different challenges:

Location Good Challenge

Fields• Site Columns• List Fields (schema.xml)

Easy to distribute platform wide If you want different behaviour on different lists then you’ll need to manually modify in the schema.xml(e.g. standard lookup on one, cascading lookup on another?)

Content Types Easy to distribute platform wide Will not fire in List Views (no .. I don’t know why either)

List View Web Part Easy to add through the browser What about people who create their own views?

List Form Web Part Easy to add through the browser What about creating list templates?

Page 20: Spca2014 js link and display templates hatch

• Your Display Templates can be placed anywhere, at the end of the day it is just some JavaScript

• If you are deploying WSP Packages, make sure your JSLink files are deployed in the same package as your Fields / Content Types / List Schemas

• Be aware of cross-site scripting protection, recommended to deploy within the site collection (i.e. instead of Azure CDN)

Deployment

Page 21: Spca2014 js link and display templates hatch

Martin Hatch

@MartinHatch

http://www.martinhatch.com

[email protected]

Thank You

Page 22: Spca2014 js link and display templates hatch