SharePoint Events

  5/13/2013 - Conference: SharePoint Summit 2013
  5/21/2013 - Webcast: SharePoint 2013 and ECM: Content Migration and Storage
  5/22/2013 - Webcast: Managing CAD in SharePoint
  5/23/2013 - Webcast: SharePoint Document Automation and E-Forms for Financial Services
  5/24/2013 - Webcast: What's New in Search for SharePoint 2013

 SharePoint Videos

  Why SharePoint 2013
  SharePoint 2013 Launch
  SharePoint 2013 Migration and Governance
  SharePoint 2013 and Enterprise Content Management
  Top Benefits of SharePoint 2013
  What's New in Business Intelligence in Office and SharePoint 2013
  SharePoint and Office 2013 Integration
  SharePoint 2013 Infrastructure Preview
  SharePoint, Lync, and, Exchange in the Cloud with Office 365
  Advanced Reporting in SharePoint with Microsoft Power View

 Archives

Opening SharePoint Links in a new windowUse SHIFT+ENTER to open the menu (new window).
Mail Enabled Lists vs. The Missing Windows 2008 POP3/IMAP Server Use SHIFT+ENTER to open the menu (new window).
7 Tools for SharePoint DevelopersUse SHIFT+ENTER to open the menu (new window).
Public Facing Masterpage TechniquesUse SHIFT+ENTER to open the menu (new window).
How to Quickly Deploy and Activate a Timer Service to Your Site CollectionUse SHIFT+ENTER to open the menu (new window).
Custom SharePoint Master Page Feature with WSP BuilderUse SHIFT+ENTER to open the menu (new window).
Date Math with InfoPathUse SHIFT+ENTER to open the menu (new window).
Enterprise Search Tricks and Tips Part 1Use SHIFT+ENTER to open the menu (new window).
Populating Word Documents With SharePoint Data. Try The DIP!Use SHIFT+ENTER to open the menu (new window).
Programmatic Deep Dive into Blank SharePoint Lookup ColumnsUse SHIFT+ENTER to open the menu (new window).
1 - 10 Next
Using the ECMAScript Client Object Model with JQuery Templates

By: Omar Stewart

In this tutorial I’m going to quickly show you how you can leverage jQuery Templates to load up data retrieved from the Client Object Model and display it using a jQuery Template. There are tons of ways to template data in SharePoint. jQuery Templates are a clean way to display and format repetitive data via JavaScript. It’s an excellent way to output data retrieved from ajax calls.

In our example, we want a simple list of the events occurring today, pulled from a standard SharePoint Calendar. Let’s jump right in and write our script to grab Today’s Events from our SharePoint calendar. 

Client Object Model Script

We’ll begin writing our script in Visual Studio, any editor will work.

The Script looks for the “Calendar” List, then fetches the items of interest using a CAML Query. We then specify which fields we’re interested in pulling from the result set.  Once we’ve successfully retrieved our results, we build an object for each result and call the jQuery Template Function. “.tmpl()”

<script type="text/javascript">

    var context = null,

            web = null,

            currentUser = null,

            calendarList = null,

            calenderEvents;

 

    function getCurrentEvents() {

 

        context = SP.ClientContext.get_current();

        web = context.get_web();

 

        //GET CALENDAR LIST

        calendarList = web.get_lists().getByTitle('Calendar');

 

        //GET TODAY'S DATE

        var d = new Date();

        var date = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();

 

        //CAML QUERY, GET ITEMS WITH TODAY'S DATE

        var queryString = "<View Scope='RecursiveAll'><Query>" +

                            "<Where>" +

                                "<Eq>" +

                                    "<FieldRef Name='EventDate' />" +

                                    "<Value Type='DateTime' IncludeTimeValue='FALSE' >" +

                                        date +

                                    "</Value>" +

                                "</Eq>" +

                            "</Where>" +

                        "</Query></View>";

 

        var query = new SP.CamlQuery();

        query.set_viewXml(queryString);

 

        //GRAB CALENDAR EVENTS BASED ON QUERY

        calendarEvents = calendarList.getItems(query);

 

        //ONLY LOAD FIELDS OF INTEREST

        context.load(calendarEvents, "Include(ID, Title, EventDate, Category)");

 

        context.executeQueryAsync(onSuccess, onFail);

    }

 

    function onSuccess() {

 

        var listEnum = calendarEvents.getEnumerator();

 

        while (listEnum.moveNext()) {

            var event = listEnum.get_current();

           

            //GET EVENT DATA

            var title = event.get_item('Title');

            var category = event.get_item('Category');

            var image = getImageForCategory(category);

 

            //BUILD EVENT DATA OBJECT

            var eventData = { Title: title, Category: category, CategoryImage: image };

 

            //RENDER EVENT USING TEMPLATE

            $("#currentEventsTemplate").tmpl(eventData).appendTo("#CurrentEvents");

        }

    }

 

    function onFail() {

        alert("Request Failed.");

    }

 

    //GET CATEGORY IMAGE

    function getImageForCategory(categoryName) {

        var imageSource = "";

 

        switch (categoryName) {

            case "Birthday":

                imageSource = "/_layouts/images/GigWerks/BirthdayCalendarEvent.png";

                break;

 

            case "Meeting":

                imageSource = "/_layouts/images/GigWerks/MeetingCalendarEvent.png";

                break;

 

            default:

                break;

        }

 

        return imageSource;

    }

 

 

    //EXECUTE FUNCTION WHEN SP.JS IS READY

    ExecuteOrDelayUntilScriptLoaded(getCurrentEvents, "sp.js");

</script>

Building the template

Now that our script is pulling in all the events for the data and passing it to jQuery to handle rendering the template, we can begin building out template.

A jQuery Template is built in a <script> block, just as if it were a normal script. For the type, we must specify “text/x-jquery-tmpl”.  Then we give our template an id, so we can tell jQuery which template we’re using for our data. For our template, we will be repeating list items, this will make for a simple template, shown below:

<script id="currentEventsTemplate" type="text/x-jquery-tmpl">

<li>

    <img src="${CategoryImage}" /> ${Title}.

</li>

</script>

 

We can add the script block right underneath the Script Block we made in the first section.

Preparing the markup

In order for the template to be displayed on the page, we need to create a container for it. Since our template repeats list items, we’ll add an unordered list as our target container.

<div>

    <ul id="CurrentEvents">

    </ul>

</div>

References

All that’s left to do now is add our jQuery references, we’ll add these at the top of the text file we’ve been using. We need to add one for the jQuery library, and another for the templating engine.

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>

Putting it all together The HTML Form WebPart

For the purposes of our tutorial, we’ll be dropping all our script into a HTML Form WebPart. This may not be an ideal practice for your scenario, but it will do just fine for the purposes of this tutorial.

Browse to your SharePoint page, click to edit the page, then insert the HTML Form WebPart.

Using_the_ECMA_Script_Client_Object_Model_with_JQuery_Templates

Then Click to edit the Form WebPart to view the Edit WebPart Pane.

Click to enter the Form’s Source Editor:

Using_the_ECMA_Script_Client_Object_Model_with_JQuery_Templates

In the Form Source Editor, paste in ALL the Content we’ve created in the previous steps.

Using_the_ECMA_Script_Client_Object_Model_with_JQuery_Templates

Save and click Okay to apply the form changes. The HTML Form WebPart will now render the items returned using the template we’ve designed:

Using_the_ECMA_Script_Client_Object_Model_with_JQuery_Templates

The Complete Script to post into the HTML Form WebPart is:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>

 

<script type="text/javascript">

    var context = null,

            web = null,

            currentUser = null,

            calendarList = null,

            calenderEvents;

 

    function getCurrentEvents() {

 

        context = SP.ClientContext.get_current();

        web = context.get_web();

 

        //GET CALENDAR LIST

        calendarList = web.get_lists().getByTitle('Calendar');

 

        //GET TODAY'S DATE

        var d = new Date();

        var date = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();

 

        //CAML QUERY, GET ITEMS WITH TODAY'S DATE

        var queryString = "<View Scope='RecursiveAll'><Query>" +

                            "<Where>" +

                                "<Eq>" +

                                    "<FieldRef Name='EventDate' />" +

                                    "<Value Type='DateTime' IncludeTimeValue='FALSE' >" +

                                        date +

                                    "</Value>" +

                                "</Eq>" +

                            "</Where>" +

                        "</Query></View>";

 

        var query = new SP.CamlQuery();

        query.set_viewXml(queryString);

 

        //GRAB CALENDAR EVENTS BASED ON QUERY

        calendarEvents = calendarList.getItems(query);

 

        //ONLY LOAD FIELDS OF INTEREST

        context.load(calendarEvents, "Include(ID, Title, EventDate, Category)");

 

        context.executeQueryAsync(onSuccess, onFail);

    }

 

    function onSuccess() {

 

        var listEnum = calendarEvents.getEnumerator();

 

        while (listEnum.moveNext()) {

            var event = listEnum.get_current();

           

            //GET EVENT DATA

            var title = event.get_item('Title');

            var category = event.get_item('Category');

            var image = getImageForCategory(category);

 

            //BUILD EVENT DATA OBJECT

            var eventData = { Title: title, Category: category, CategoryImage: image };

 

            //RENDER EVENT USING TEMPLATE

            $("#currentEventsTemplate").tmpl(eventData).appendTo("#CurrentEvents");

        }

    }

 

    function onFail() {

        alert("Request Failed.");

    }

 

    //GET CATEGORY IMAGE

    function getImageForCategory(categoryName) {

        var imageSource = "";

 

        switch (categoryName) {

            case "Birthday":

                imageSource = "/_layouts/images/GigWerks/BirthdayCalendarEvent.png";

                break;

 

            case "Meeting":

                imageSource = "/_layouts/images/GigWerks/MeetingCalendarEvent.png";

                break;

 

            default:

                break;

        }

 

        return imageSource;

    }

 

 

    //EXECUTE FUNCTION WHEN SP.JS IS READY

    ExecuteOrDelayUntilScriptLoaded(getCurrentEvents, "sp.js");

</script>

 

<script id="currentEventsTemplate" type="text/x-jquery-tmpl">

<li>

    <img src="${CategoryImage}" /> ${Title}.

</li>

</script>

 

<div>

    <ul id="CurrentEvents">

    </ul>

</div>

 

I hope this has been a helpful introduction.

By: Omar Stewart

        

Comments

There are no comments yet for this post.
Items on this list require content approval. Your submission will not appear in public views until approved by someone with proper rights. More information on content approval.

Your Name *


e-mail address *


Website (optional)


Comment *


Attachments

 Subscribe

  GigWerks RSS  Gig Werks Mailing List 

 Contact Us

 Connect

 Resources

  On Demand SharePoint Webcast Recordings
  Upcoming Webinars
  SharePoint Resources
  Business Intelligence Resources
  Gig Werks Website



©2009 Gig Werks. All rights reserved. Privacy Policy