Close

Not a member yet?Register now and get started.

lock and key

Sign in to your account.

Account Login

How to use jQuery Templates and JSON APIs with jQuery Mobile

15 Dec. 2011 Posted by Shane Gliser in mobile, jquery mobile, json, jquery templates

You want to use APIs? Want to create dynamically pages on the fly? Want to do it without overwhelming the browser? Here's how....

Note: Here is this same example done with jsRender. jsRender is now the stated direction for templating by the jQuery team. Thanks to @ziodave for pointing this out. Despite that, I am leaving this original post intact because it may still be useful to somebody.

Author's Note:

Creating Mobile Apps with jQuery Mobile by Shane GliserPackt Publishing recruited me to write a book on jQuery Mobile!

Once you've read this article and found it useful, you should order my book. It's full of real world examples that span several industries and technologies using jQuery Mobile. The eBook editions are cheap and obviously, you know where to come if you have follow up questions ;-)

Check out Creating Mobile Apps with jQuery Mobile

For the base page, let's start out with the basic starting page from jquery mobile.

For an API, let's go with the example for getJSON from jQuery.

Next, call in the tempalte engine scripts...
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>

Then, create a spot for your templated content to live...
<script id="flickrTemplate" type="text/x-jquery-tmpl">

When we make our getJSON call, we'll transform the contents of the template with the returned data from the API call and add it wherever we like.
$("#flickrTemplate").tmpl(data).appendTo(document.body);

Here is the finished code but please don't stop at just viewing the source, I've got a few key takeaways afterwards.

view this example in action

Important consideration for creating dynamic pages in jquery mobile

  • jQuery Mobile does not (by default) instantly remove dynamically created pages like it does with pages that are simply ajaxed in through normal page-to-page navigation. This can be a blessing and a curse. It gives you something to go back to quickly so you don't have to re-render the content. However the more pages you create the closer you come to the point where your poor little mobile phone wont be able to take the strain due to the number of DOM elements. To make dynamically generated pages auto-remove like normal pages would, you'll need to execute this line of script from the example.
    newpage.attr( "data-" + $.mobile.ns + "external-page", true ).one( 'pagecreate', $.mobile._bindPageRemove );



  • The source shows two differnet $.mobile.changePage calls.

    The first one: $.mobile.changePage("#"+data.pageId); will find the page through selectors and then transition to. The change will also be reflected in the URL and thus show up in history.

    The second one: $.mobile.changePage(newpage); is being passed a direct jquery object reference to the page. Using this method will cause a page transition to the new content but will not affect the URL and thus not show up as an update in history.


  • jQuery Template content is held within a script tag and refernced by ID. <script id="flickrTemplate" type="text/x-jquery-tmpl"> jQuery Mobile does not try to parse or enhance the contents of these script files. The example is a single page example, even with these templates. It is not until templates are transformed with the data and the results are appended to the DOM that you can navigate to the pages.


  • This example is creating full pages. However, there is no reason that you could not use these same techniques to create page fragments and inject them into any portion of any jquery mobile page. For instance, if you were hitting some API on a regular interval and only updating a page's listview, you could simply use a template transformation and replace or append to the current listview and then call $("#some_list").listview("refresh");


  • jQuery Templates are relatively simple to use and have some powerful controlls including normal programming structures like if, else, and each loops. To get the most of our them, you should really read up on the template APIs and examples.

I hope you found this helpful. As always, you can leave a comment or send a message to hello@roughlybrilliant.com.

Now, go be brilliant!

Comments

Submitted by Trygve (not verified) on Thu, 12/29/2011 - 14:45 #

Have you noticed issues of page transitions on the iPhone with dynamically injected pages (http://jquerymobile.com/test/docs/pages/page-dynamic.html)? If so have you found any work arounds?

Submitted by Shane Gliser on Sun, 01/01/2012 - 11:56 #

Actually, I don't really have any kind of page transition issues with this example.

If I'm not mistaken, the problem you reference is... "Now an interesting problem here is that jQuery Mobile typically updates the browser's location hash with the URL associated with the page it is showing. Because we are re-using the same page for each category, this wouldn't be ideal, because the URL for that page has no specific category info associated with it."

I did not have this issue because I'm not reusing the same page over and over as they are. I can understand why they'd do that. It keeps the DOM size small, but I'm getting around that issue a different way. I create a new page each time based off a single template and give it a unique ID. After creating the new page, I'm marking it for deletion on exit as if it were loaded by ajax. (check my code to see how I did it). The result is a multi-page template that behaves more like an ajax based site. Therefor, it avoids any page transition issues.

Did you have any particular example you were needing help with? I'd be happy to have a look.

Submitted by Trygve (not verified) on Tue, 01/03/2012 - 10:04 #

I also just noticed that the back button behavior is not ideal. I ran your search for "cats" then at the bottom of the results I ran a "dogs" search. Clicked back to #cats but still had the dogs DOM items. I'm sure this was just a quick example for your blog. I'll try it without marking the page for deletion. Thanks again.

Submitted by Trygve (not verified) on Tue, 01/03/2012 - 09:57 #

Thanks for the info Shane. Your example isn't rendering properly on my iPhone4 (iOS5). The page loads but is "un-jQm-styled". Desktop safari/chrome is fine. Just me/my phone?

Their example uses the pagebeforechange event. I'll try your pageint approach. It's the main difference between my example and yours (I'm also saving new pages in the DOM). I modified their example to first look if the page exist and if not dynamically inject one. I have the case where users will often return to previous pages (employee directory) and I wanted to keep the pages to avoid the delay of another ajax/rending call.

Another difference is I'm using jsRender for my templates and 1.7.1. Not sure if this has any impact or not. If I still see issues I'll post my example. Thanks again for contributing to the community.

Submitted by Shane Gliser on Wed, 01/04/2012 - 10:18 #

Submitted by Shane Gliser on Tue, 01/03/2012 - 10:18 #

I didn't fully flush out the thing to be production ready ( or even QA ready ) by accounting for every circumstance. I never built in the hooks to make it pull a search term directly from the URL on page navigation. It is doing a search that makes it call to flick for now.

As for showing the dogs again, If you try to navigate to an "page" that doesn't exist, it shows what you were just on.

It's like you said, this was just a quick example for the blog to give people a starting point and hopefully answer some of the kinds of questions I've seen floating around out there in the community. If you create an example using JSRender I'd love to see it. That was my next goal by the end of this week.

Submitted by Alin (not verified) on Fri, 01/13/2012 - 10:30 #

Thank you Shane.

Submitted by Diego (not verified) on Thu, 05/10/2012 - 15:29 #

Hi everybody, I have a question on the history after the page removal. Let's say I have dinamically generated content from json files and I can go deeper than 1 level (unlike the app example here). I need to remove the pages from the dom since it becomes too heavy for a mobile device, but at the same time I want to keep track of the history.
Right now, if I go down to a 3rd level in my tree, I removed the pages from level 1 and 2. If I hit the back button I can go back only to page 2 but I lose the ability to go back to page 1 and 0.
How can I keep the path 0,1,2,3 in the history without having to keep the pages in my dom? Is there any simple solution to this?

Thanks
Diego

Submitted by Eric W (not verified) on Thu, 08/16/2012 - 06:13 #

Thank you. This actually was a lot more helpful than the JQM docs for me. I'm putting the json data into a dialog instead of a page, so this worked great.

Submitted by wdesarn (not verified) on Tue, 09/04/2012 - 00:13 #

Totally good post, the article gave a lot of information. Thank you

Submitted by Anonymous (not verified) on Wed, 10/23/2013 - 02:50 #

Good Post.Thank You.

Post new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
Are you a human? Let's just be sure...