My studying notebook

Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

2011/09/04

[Notebook] Using jQuery templates in Google AppEngine

9/04/2011 10:52:00 PM Posted by Unknown , , , , , , 344 comments
jQuery is a powerful javascript library that you can improve web browser experience just add some js codes. jQuery also has a lot of useful plugin you can add. lightbox, autocomplete etc.

jQuery supports Templates plugin now that you can render HTML code very simply. Here has very detail document and tutorial. Today, i will talk about how to use jQuery templates in Google AppEngine. What is the problem using jQuery templates in Google AppEngine web application.? Braces {}.

Templates syntax.
Google AppEngine Django template.
{% for item in objs %}
 {{item}},
{% endfor %}

jQuery Templates
<script id="doclistTmp" type="text/x-jquery-tmpl">
        {{each(i, o) obj}}
        <tr class="{{if i%2== 0}}odd{{else}}even{{/if}}">
            <td> ${title}</td>
            <td>${type}</td>
            <td>${folders}</td>
        </tr>
        {{/each}}
</script>

They both use brases is problem that you will meet it if you want to use jQuery templates via ajax in Google AppEngine. Then, how to setup jQuery templates in Google AppEngine.

Step1.
Register a tag in a py file called "verbatim_templatetag.py" {{if condition}} print something{{/if}}. Tell Django don't change anything within this tag.
"""
jQuery templates use constructs like:

    {{if condition}} print something{{/if}}

This, of course, completely screws up Django templates,
because Django thinks {{ and }} mean something.

Wrap {% verbatim %} and {% endverbatim %} around those
blocks of jQuery templates and this will try its best
to output the contents with no changes.
"""

from django import template

register = template.Library()

class VerbatimNode(template.Node):

    def __init__(self, text):
        self.text = text

    def render(self, context):
        return self.text

@register.tag
def verbatim(parser, token):
    text = []
    while 1:
        token = parser.tokens.pop(0)
        if token.contents == 'endverbatim':
            break
        if token.token_type == template.TOKEN_VAR:
            text.append('{{')
        elif token.token_type == template.TOKEN_BLOCK:
            text.append('{%')
        text.append(token.contents)
        if token.token_type == template.TOKEN_VAR:
            text.append('}}')
        elif token.token_type == template.TOKEN_BLOCK:
            text.append('%}')
    return VerbatimNode(''.join(text))

Step2.
Include custom tag in your py file that you use web template
 template.register_template_library('verbatim_templatetag') 

Step3.
Add you jQuery template to html page.
 {% verbatim %}
        <script id="movieTemplate" type="text/x-jquery-tmpl">
            <tr>
                <td>${posted}</td>
                <td><a href="${link}">${response_count}</a></td>
                <td>{{html content}}</td>
            </tr>
        </script>
 {% endverbatim %} 

Step.4
call jQuery templates.
  $("#movieList").html($("#movieTemplate").tmpl( plurks )); 


Reference

2008/11/03

jQuery intellisense in VS2008

11/03/2008 10:21:00 PM Posted by Unknown , 1 comment
It is old news. Scott Guthrie announce that Microsoft will be shipping jQuery with Visual Studio going forward. It's a good news for developer of ASP.NET. We can use lightweight open source javascript library to do more rich interative application in the client side. It's a important feature that Visual Studio 2008 support full javascript support. And few days ago, microsoft had release a hotfix for a number of issuse in Visual Studio 2008. You can make Visual Studio's javascript intelliense work better with jQuery.

scenario
  1. download visual studio hotfox(KB946581) and install
  2. download jquery intellisense file
    Untile now, I search few atrical about jQury intellisense in VS2008. In order to use jQury intellisense. We must download another javascript(jQuery intellisense file). i donwload the intellisense file from(this) before i find jQuery web site support documentation(jquery-1.2.6-vsdoc.js) in Visual studio


  3. Add both file(jQuery, intellisense) to your web page


Ps. About web page import javscript, usually we direct asign script block src attribute. Another method, we can use Google AJAX Libraries API load jquery file. It's more convenience to load jquey library by Google AJAX Libraries API. For example: you can change jquery library version by modify aip parameter.
//using 1.2.3 version jquery
google.load("jquery", "1.2.3");
// useing 1.2.6 version jquery
google.load("jquery", "1.2.6");

OH! sure. you still can add other js file by Google AJAX API. ex: jqueryui

2008/07/02

Google AJAX Feed API - AJAX Slide Show Rolling

7/02/2008 07:00:00 PM Posted by Unknown , , , , , 4 comments
AJAX Slide Show 為利用Google AJAX Feed API作出來簡單的應用。允許使用者把 PhotoBucketFlickrPicasa Web Albums的網路相簿以幻燈片的方式嵌在自己的Blog、網站等中。在Slide Show 中Picasa Web Album Feed URL無法動態更改,利用Picasa Web Albums Data API 與 jQurey JSON的操作,即可完成Picasa Web Albums的輪播。


Live Demo
| Download


AJAX Slide Show
<script type="text/javascript">
function load() {
var samples = "http://dlc0421.googlepages.com/gfss.rss";
var options = {
displayTime: 2000,
transistionTime: 600,
linkTarget: google.feeds.LINK_TARGET_BLANK
};
new GFslideShow(samples, "slideshow", options);
}
google.load("feeds", "1");
google.setOnLoadCallback(load);
</script>

var samples 為載入相關的Rss,在Picasa Web Album中都可以訂閱任何一個相簿的Feed。例如訂閱第七屆拼圖馬拉松的Feed(http://picasaweb.google.com/data/feed/base/user/cage.chung/albumid
/5217479087123706369?kind=photo&alt=rss&hl=en_US
)即可將此相簿以Slide Show的方式展示在網頁中。


AJAX Slide Show Advance

scenario
上述的方式,Side Show相簿的Feed為固定的,如果想要展示不同的相簿就必需更改程式碼,這是一件滿煩麻的事情。即然Google公開了Picasa Web Albums Data API,所以我們應該可以使用API搜尋特定user的相簿,以亂數組出Slide Show所需的Feed,達到相簿輪播的效果。

待解決的問題:
  • 選擇Ablum Feed Url
  • 決定Picasa Web Albums Data API回傳資料的格式及接收方式
  • Parser回傳的資料,找出組出Feed最主的資料(Picase Web Album ID)
  • 將亂數選出的Ablum ID帶入AJAX Slide Show

Step1
我們可以要求幾種來自Picase Web Ablum的不同的Feed。依照我們的需求,是搜尋特定user所有公開的相簿,在Picasa Web Albums 搜尋的參數[1]中會使用到kind與access2種參數
  • Kinds指特定類別的參數(ablum、photo、comment、tag、user)在此使用, user
  • Access指定相簿屬性(all、public、private)在此指定user所有公開的相簿, publick
因此,我們Ablum Feed Url則為http://picasaweb.google.com/data/feed/api/user/userID?kind=kinds&Access=publick

Step2
由於 AJAX 程式中的 XMLHttpRequest 只能呼叫同一個 domain 下的 URL,所以呼叫遠端並回傳XML資料型態的資料會以安全性考量被拒絕存取。又因為Picasa Web Albums資料格式提供另一種輕量級的資料交換格式(JSON),只有在Feed Url中指定alt=json即可將XML資料格式轉換成JSON格式並回傳。

選定遠端資料回傳格式為JSON,剩下的就是本機端該如何接收JSON型態資料。在此使用了一個新形態的 JavaScript程式庫(jQuery),程式庫中可以直接使用 jQuery.getJSON( url, [data], [callback][2] 操作JSON並進行AJAX回呼。此時的Ablum Feed Url更改為http://picasaweb.google.com/data/feed/api/user/cage.chung?kind=album&access=public
&alt=json&callback=?


Step3
剩下的部份就是Parser回傳的JSON資料
var numentries = json.feed.entry.length; //每一個相簿都是單獨的entry,numentries則為相簿的數量
var rNum = Math.floor(Math.random() * numentries); //以Random選擇相簿
var item = json.feed.entry[rNum];

var title = item.title.$t; //相簿的標題
var summary = item.summary.$t; //相簿的說明
var id = item.gphoto$id.$t; //最主要的相簿ID


Step4
將亂數選出的Ablum ID帶入AJAX Slide Show var samples 字串中即可




整合之後的Script 如下
<script type="text/javascript">
function load() {
$.getJSON("http://picasaweb.google.com/data/feed/api/user/<span style="
font - weight: bold;
">USERID</span>?kind=album&access=public&alt=json&callback=?", function(json) {

var numentries = json.feed.entry.length;
var rNum = Math.floor(Math.random() * numentries);
var item = json.feed.entry[rNum];

var title = item.title.$t;
var summary = item.summary.$t;
var id = item.gphoto$id.$t;

if (summary.length > 0) $("#msg").html("<h4>" + title + "</h4><p>" + summary + "</p>");
else $("#msg").html("<h4>" + title + "</h4>");

var samples = "http://picasaweb.google.com/data/feed/api/user/<span style="
font - weight: bold;
">USERID</span>/albumid/" + id + "?kind=photo&alt=rss&hl=en_US";

var options = {
displayTime: 2000,
transistionTime: 600,
linkTarget: google.feeds.LINK_TARGET_BLANK,
scaleImages: true
};
new GFslideShow(samples, "slideshow", options);
});
}
google.load("feeds", "1");
google.setOnLoadCallback(load);
</script>




Reference
  1. Interacting with Picasa Web Albums
  2. you can load JSON data located on another domain if you specify a JSONP callback, which can be done like so: "myurl?callback=?". jQuery automatically replaces the ? with the correct method name to call, calling your specified callback. Or, if you set the dataType to "jsonp" a callback will be automatically added to your Ajax request.
  3. Projection values: Feed URL "api" 與 "base"的差別,api參數提供了gphoto相關元素(包括我們需要的album id)
base
api