Tuesday, October 05, 2010 6:30 PM Jan Tielens

Getting Started with jQuery Templates and SharePoint 2010

Yesterday evening Scott Guthrie announced that Microsoft’s contributions to the jQuery Javascript library were accepted as Official jQuery plugins. One of those contributions is the jQuery Template plugin that allows you to do (up to a certain level) something like data binding similar to the approach we know from Silverlight. The idea is to create a template (think HTML snippet with elements bound to data properties) and data bind that template with an array of objects. You can find the API documentation over here, or you can check out Boris Moore’s excellent Getting Started guide.

So how can we leverage this in SharePoint 2010? Well jQuery Templates are a great match for either the SharePoint 2010 ECMAScript/Javascript Client Object Model, or the SharePoint 2010 REST API. The following example shows how to quickly display a list of Tasks on a page, by only using jQuery and the REST API in SharePoint 2010. Let’s start with a very basic Site Page that puts an empty ul element in the PlaceHolderMain Content control (notice the ul element gets a specific id set):

<%@ Page MasterPageFile="~masterurl/default.master" %>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <ul id="tasksUL"></ul>
</asp:Content>

Next, we need to put some script references in the PlaceHolderAdditionalPageHead Content control to load both the jQuery library and the jQuery Templates plugin. For now this plugin is a separate .js file, in the next release of jQuery this plugin becomes a part of jQuery itself. (The demo code assumes that both .js files are deployed to the same location as the Site Page.)

<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script src="jquery-1.4.2.min.js" type="text/javascript"></script>
    <script src="jquery.tmpl.js" type="text/javascript"></script>
</asp:Content>

After the script references (also in the PlaceHolderAdditionalPageHead Content control), we need to define our template, also using a script element that has the type attribute set to text/x-jquery-xml. This template is just an HTML snippet that gets created for every object of the array that gets “data bound”. In the template it’s possible to use references to those object’s properties by using template tags. For example ${Title} will get the value of the Title property of the object that gets “data bound”. In the sample below, I’m defining a template that’s basically an li element which displays some properties of a SharePoint Task item. Notice that to display the Description of the Task, I’m using the {{html}} Template Tag, because Description is a Rich Text Field thus it contains HTML itself.

<script id="tasktemplate" type="text/x-jquery-tmpl">
    <li>
        <b class="ms-rteFontSize-4">${Title}</b> - ${StatusValue}
        <div>{{html Description}}</div>
    </li>
</script>

Finally, in a new normal script element (once again in the PlaceHolderAdditionalPageHead Content control), we can use jQuery’s getJSON function to make an async call to the REST API. The getJSON function takes as a parameter a URL to call, which will be the URL of the listdata.svc (= REST API end point) that fetches all Tasks that are not yet completed. The last parameter of the getJSON function is a callback function that will use the jQuery Templates mechanism to build a new li element for every retrieved Task item, based on the template we defined above. This is accomplished by using the new tmpl function, called on the template. The return value is an array of DOM elements, which are added to the empty ul element, defined above.

<script type="text/javascript">
    $(document).ready(function () {
        $.getJSON(
            "../_vti_bin/listdata.svc/Tasks?$filter=StatusValue ne 'Completed'", null,
            function (data) {
                $("#tasktemplate").tmpl(data.d.results).appendTo("#tasksUL");
            });
    });
</script>

Once the Site Page is deployed, the result will look as follows:

 

If you’re interested, I’ve created a (slightly enhanced) sample Visual Studio project that’s a Sandboxed Solution (download here, including source code). This project provisions the required .js files, and the Site Page. On the demo Site Page I’ve used the following template:

<script id="tasktemplate" type="text/x-jquery-tmpl">
    <li>
        <b class="ms-rteFontSize-4" style="cursor:pointer;">
            ${Title}</b> - ${StatusValue}
        <div style="display:none">{{html Description}}</div>
    </li>
</script>

Notice that the div element that shows the Description value, is using the style display:none; so initially the Description value is not being displayed. In the callback function, after the li items are built, I’m using jQuery’s toggle function to show and hide the Description div when the corresponding Title is clicked.

$("#tasktemplate").tmpl(data.d.results).appendTo("#tasksUL");
$("#tasksUL li").toggle(
    function () {
        $(">div", $(this)).show("fast");
    },
    function () {
        $(">div", $(this)).hide("fast");
    }
);

When the Sandboxed Solution is deployed and activated, just navigate to the demo page using the URL http://yoursite/TemplateDemoAssets/demopage.aspx. You’ll see a nicely animated list of Tasks that are not yet completed!

Filed under:

Comments

# re: Getting Started with jQuery Templates and SharePoint 2010

Tuesday, October 05, 2010 9:53 PM by Christophe

This also looks a lot like XSLT.

What is not clear for me is the role of the type attribute text/x-jquery-xml. Is it a standard, and is it recognized by all browsers?

# re: Getting Started with jQuery Templates and SharePoint 2010

Wednesday, October 06, 2010 1:05 AM by Jan Tielens

Christophe, IMHO the attribute is used to make sure the browser doesn't execute the script in that element. Since jQuery is cross browser compat. I assume the Templates will work on all modern browsers.

# re: Getting Started with jQuery Templates and SharePoint 2010

Wednesday, October 06, 2010 11:04 AM by Paul

How will this function without Javascript? Or if you need to follow the accessibility guidelines?

In other words, what is the fallback?

# re: Getting Started with jQuery Templates and SharePoint 2010

Wednesday, October 06, 2010 11:24 AM by Jan Tielens

Paul, it won't work without Javascript. The page doesn't have a fallback mechanism.

# re: Getting Started with jQuery Templates and SharePoint 2010

Thursday, October 14, 2010 3:01 AM by wow gold

Tropical flowers, smiling skull, pistols, treasure chest and submarines elements together, sweet and personality, but not black humor, but the super sunny. The use of colored gemstones is also very agile, with enamel coating color contrast echo.

# re: Getting Started with jQuery Templates and SharePoint 2010

Thursday, October 14, 2010 5:01 AM by brass casting

It is very good that Microsoft’s contributions to the jQuery Javascript library were accepted as Official jQuery plugins

# re: Getting Started with jQuery Templates and SharePoint 2010

Thursday, October 14, 2010 10:37 PM by Rob

Will this technique work with Safari and Chrome, and is this specific to 2010?

I tried a similar jQuery example with MOSS 2007 and the output worked fine in IE and Mozilla browsers, but failed on Safari and Chrome. Any advice is appreciated. (weblogs.asp.net/.../querying-sharepoint-list-items-using-jquery.aspx)

# re: Getting Started with jQuery Templates and SharePoint 2010

Wednesday, November 03, 2010 4:32 PM by jayman723

Using smart part but can only see images if I have a local admin account? Please help!

# re: Getting Started with jQuery Templates and SharePoint 2010

Thursday, November 11, 2010 3:48 PM by WerbakovEvgenij

Расскажите пожалуйста, что значит [url=www.bustrans.com.ua/.../4]аренда автобусов[/url] и где именно такую услугу можно найти! Спасибо большое.

# re: Getting Started with jQuery Templates and SharePoint 2010

Friday, November 12, 2010 6:18 AM by write my term paper

The literature essays creating would not always be a fun. The original essay will take a long time. Smart people would recommend to purchase essays. I guess that this is the correct way.

# re: Getting Started with jQuery Templates and SharePoint 2010

Saturday, November 13, 2010 7:20 AM by thesis

I will affirm that you do very the finest stuff just about this good topic. You have to make the thesis samples for thesis service or create your buy dissertation service and some students will buy a thesis paper in that location.                              

# re: Getting Started with jQuery Templates and SharePoint 2010

Monday, November 15, 2010 5:55 AM by order writing

If you attempted to finish your essays, then you should be aware of how hard it's! But, don't lose your expectations because you can rely on the writing custom papers  service.  

# re: Getting Started with jQuery Templates and SharePoint 2010

Monday, November 15, 2010 6:41 AM by perfect custom papers

Guys have lost their trust in term papers writing companies, just because there're a lot of scams in the web. Nonetheless, we ought not to be pessimists because it's possible to determine a reliable place to say: "I will pay someone to write my paper ".  

# re: Getting Started with jQuery Templates and SharePoint 2010

Monday, November 15, 2010 12:42 PM by buy essays

A lot of students choose to buy an essay at the research paper writing service just about this topic.  

# re: Getting Started with jQuery Templates and SharePoint 2010

Tuesday, November 16, 2010 1:35 AM by term paper help

proficient that people has eventually developed a self empowerment order that is customarily honest and, yet, simple, joy, and available. They should use  online papers aid

# re: Getting Started with jQuery Templates and SharePoint 2010

Tuesday, November 16, 2010 2:33 AM by essay editing service

There're lots of complications along the career building road. But, the buy essays service was invented to support high school students with custom research papers creating.

# re: Getting Started with jQuery Templates and SharePoint 2010

Tuesday, November 16, 2010 2:59 AM by coursework help

Do not waste your leasure time for coursework completing if you are not an expert. You should betterbuy coursework.  

# re: Getting Started with jQuery Templates and SharePoint 2010

Wednesday, November 17, 2010 9:44 AM by Arjan Fraaij

Hello Jan,

Should it be possible to use JQuery to change the behaviour of the MySite link? I would like it to make sure when I click the MySite link in SharePoint 2010 to open in a new browser tab or window. SharePoint 2007 could this be done by editing the MySiteLink.ascx, in 2010 the file is not there any more.

If you like can you create an example :-)

Regards,

Arjan

# re: Getting Started with jQuery Templates and SharePoint 2010

Wednesday, November 17, 2010 10:12 AM by dissertation writing service

If you don't cruise after what you want, you'll never have it. If you don't request, the reply is continually no. If you don't get used to   thesis writing service , you're continually in the same place.

# re: Getting Started with jQuery Templates and SharePoint 2010

Thursday, November 18, 2010 2:41 AM by custom essays

Usually some persons do really know how to compose the custom essays. But when you are not master papers writer, you should seek the reliable order essays service to buy your customized research paper with the goal to have a success.

# re: Getting Started with jQuery Templates and SharePoint 2010

Monday, November 22, 2010 12:17 PM by Research papers

I will affirm that you do very the finest stuff just about this good topic. You have to make the thesis samples for thesis service or create your buy dissertation service and some students will buy a thesis paper in that location.  

# re: Getting Started with jQuery Templates and SharePoint 2010

Wednesday, November 24, 2010 2:48 PM by electric guitar

I like to acquire breaks during the my day and look by means of some blogs to view what people are stating. This weblog appeared in my searches and that i could not support but clicking on it. I'm glad I did since it was a quite enjoyable learn.

--------------------------------------------

my website is  

http://violin-lesson.info

Also welcome you!

# re: Getting Started with jQuery Templates and SharePoint 2010

Tuesday, November 30, 2010 1:17 AM by &#27931;&#26441;&#30710;&#30041;&#23398;&#29983;

"Super-Duper internet site! I am loving it!! Will appear back again once again - getting you feeds also, Thanks."

--------------------------------------------

<a href="xiangyan.info/-c-71.html">&

Also welcome you!

# re: Getting Started with jQuery Templates and SharePoint 2010

Wednesday, December 01, 2010 5:59 AM by theses

The teacher says that we will have to stab below into ourselves and pay attention to scan what we really are. But I think it would be more suitableto use thesis help.

# re: Getting Started with jQuery Templates and SharePoint 2010

Tuesday, December 07, 2010 6:51 AM by thesis writing

Any projects that have received complete funding or even pipeline funding are often disclosed. This causes future researchers to have a general idea of a funding body’s interests.

# re: Getting Started with jQuery Templates and SharePoint 2010

Wednesday, December 08, 2010 6:23 AM by Order essay

Purchase only quality school written essay.    

Buy cheap essay. We offeronly quality custom    term papers.  

<a href=www.orderessay.net/essay-writing.html>Essay writing</a>  service for  Australia  students.

# re: Getting Started with jQuery Templates and SharePoint 2010

Tuesday, December 14, 2010 10:31 AM by Order essay

Buy best quality custom written paper.        

Buy good paper. We offeronly quality custom    

essays.      

<a href=livepaperhelp.com/writeresearchpaper.html>Writing research papers</a>??? No problem! our service help to YOU!

# re: Getting Started with jQuery Templates and SharePoint 2010

Tuesday, December 14, 2010 10:45 AM by Writing Service

Buy only quality school written paper.        

Buy good paper. We offertop quality custom    

dissertation.      

Custom <a href=livepaperhelp.com/college-essays.html>college essays</a> are written by  professional    writers who know how to write an impressive essay.

# re: Getting Started with jQuery Templates and SharePoint 2010

Wednesday, December 15, 2010 2:57 AM by Windows 7 Product Key

I thought it was going to be some boring old post, but it really compensated for my time. I will post a link to this page on my blog. I am sure my visitors will find that very useful.

# re: Getting Started with jQuery Templates and SharePoint 2010

Wednesday, December 15, 2010 4:35 AM by MCITP Training

Very much appreciative.

# re: Getting Started with jQuery Templates and SharePoint 2010

Friday, December 17, 2010 2:59 AM by air jordans

Intimately, the post is actually the best on this laudable topic. I harmonize with your conclusions and will eagerly look forward to your future updates. Saying thanks will not just be adequate, for the fantastic lucidity in your writing.

# re: Getting Started with jQuery Templates and SharePoint 2010

Friday, December 17, 2010 3:04 AM by air jordans

Thanks for sharing your article. I really enjoyed it. I put a link to my site to here so other people can read it. My readers have about the same interets

# re: Getting Started with jQuery Templates and SharePoint 2010

Saturday, December 18, 2010 3:35 AM by killer ipad app

You can't judge a tree by its bark.

-----------------------------------