🍃このブログは移転しました。
3秒後、自動的に移動します・・・。

Handlebars.jsとTwitter Search APIを使ったサンプル

いま絶賛勉強中のHandlebars.jsを使って、TwitterAPIを絡めたサンプルを。
Handlebars.jsについては、また備忘録を残そうかと思ってます。

概要

  • TwitterのSearch APIを叩く
  • 取得したjsonを、Handlebarsのテンプレに流しこむ

簡単!

ソース

Html / Css

<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Handlebars x Twitter API</title>
<style>
body{
  text-align: center;
  margin: 0;
  padding: 0;
}
#container{
  width: 50%;
  margin: 0 auto;
  padding: 20px;
  background: #eee;
}
.tweets{
  clear: both;
  height: 42px;
  margin:0 0 20px;
  overflow: hidden;
}
.tweets:hover{
  height: auto;
}
.tweets p{
  margin: 0;
}
.tweets img{
  display: block;
  float: left;
  margin-right: 5px;
}
</style>
</head>
<body>
<h1>Handlebars.js with Twitter Search API</h1>
<div id="container">
  <input type="text" id="q" />
  <button id="reload">Search</button>
  <script id="input" type="text/x-handlebars-template">
    {{#each this}}
    <div class="tweets" title="@{{user}}'s tweets">
      <img src="{{url}}" width="42" height="42" />
      <p>{{text}}</p>
    </div>
    {{/each}}
  </script>
  <div id="output"></div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.js"></script>
<script><!-- 下のコード --></script>
</body>
</html>

Cssはオマケで。

JavaScript(jQuery)

(function() {

    var Twitter = {},
        source = $("#input").html(),
        template = Handlebars.compile(source);

    Twitter.init = function(conf) {
        $.ajax({
            type: 'GET',
            url: 'http://search.twitter.com/search.json',
            dataType: 'jsonp',
            cache: true,
            ifModified: true,
            data: {
                q: conf.query,
                lang: 'ja',
                locale: 'ja-JP',
                result_type: 'mixed',
                rpp: 100
            },
            success: function(d) {
                var tweets = $.map(d.results, function(d) {
                    return {
                        user: d.from_user,
                        url: d.profile_image_url,
                        text: d.text
                    };
                });
                $("#output").html(template(tweets));
            }
        });

    };

    $('#reload').on('click', function() {
        $('#output').empty();
        Twitter.init({
            query: $('#q').val()
        });
    });

    Twitter.init({
        query: "Get better"
    });
}());

説明とか

  <script id="input" type="text/x-handlebars-template">
    {{#each this}}
    <div class="tweets" title="@{{user}}'s tweets">
      <img src="{{url}}" width="42" height="42" />
      <p>{{text}}</p>
    </div>
    {{/each}}
  </script>

  <div id="output"></div>

そのままですが、idがinputの中がテンプレです。
{{}}でくくります。
eachとかifとかunlessとか使えます。
今回はthisになってますが、もちろんプロパティの名称を指定することもできます。

var source = $("#input").html();
// 作ったテンプレの元を取得してー
var template = Handlebars.compile(source);
// それをテンプレとしてコンパイル!

 $("#output").html(template(tweets));
// 最後にそれを出力!

とまぁお手軽3ステップですね。