In this post I'd like to share another approach how to get data in SharePoint hosted app for anonymous users. It uses a XsltListViewWebPart, as it gets data on server side, store it in a JS variable that is used in CSR.
Thus you can override CSR of a view or make it hidden and just use it as a datasource.
In general we have the following algorithm to make it working:
- Create a list or a library
- Create a custom View (or use All Items)
- Customize rendering template as you need
- Place XsltListViewWebPart on an App page, configure it to use appropriate View and rendering template
I've created a simple list based on a Contact list template and added a new view called "Customized by CSR", it has a BaseViewID set to "3". Actually BaseViewID is a non unique integer that can be set to any number you like. Using this number, it's really easy to provision views to site pages (you will see an example below). But please take into account that some values may not work and throw error - just use another number to make it work. You can read more here.
Also I set JSLink to a script file with my CSR function to customize the page as required.
Provision page with XsltListViewWebPart
First of all I need to insert a Web Part Zone into my default.aspx page, zone is called "Main".
I use module to provision view to a page as the easiest approach for SharePoint hosted apps, List property defines url of the list I want to work with, BaseViewID defines the view of the list, WebPartZoneID defines the place where to add view on the page (there can be multiple zones), WebPartOrder defines the order with the zone (starts from 0 - the toppest in the zone). Inside View we can specify any properties of XsltListViewWebPart. In my case I like to disable switching views and searching.
The final thing is customization of CSR to display items the way we like. Please note this code is just an example :)
You can find live demo here.
You can download the App
and its code on https://spsitepro.codeplex.com