LoginSignup
29
34

More than 5 years have passed since last update.

jQueryにテンプレートシステムを導入するjQuery-templateの使い方

Last updated at Posted at 2015-08-12

背景

jQueryでよくやるやつだと、$.getJSONでデータ取って、HTMLに値をズコズコ突っ込んでいくやつですね。

$.getJSON('hoge.com',function(json){
    $("#name").text(json.data.name);
    $("#address").text(json.data.address);
});

テンプレート化したいときも

リスト表示みたいに数が未定で、1つテンプレート用意して
それを複製したいときなどもありますね。
こんな感じですかね―。
ちょっと苦しい。

var template = '' +
'<div>' +
  '<div id="name"></div>' +
  '<div id="address"></div>' +
'</div>';

$.getJSON('hoge.com',function(json){
    $(template).find('#name').text(json.data.name);
    $(template).find('#address').text(json.data.address);
});

そんなときにjQuery-Templateです。

上記からcloneしたら
jquery.loadTemplate-x.x.x.min.js
をjsフォルダに突っ込んでHTMLに読み込んでください。

基本の使い方

まずはテンプレートとなるHTMLを用意します。

user.html

<div>
  <div data-content="name"></div>
  <div data-content="address"></div>
</div>

地味に嬉しいのが、jQueryなのにidやclassを使わないで、data-contentを使って変数を入れる所。これだったら、デザイナーさんと作業が切り離せますね。

getJSONから呼び出します。

$.getJSON('hoge.com',function(json){
    $("#area_user").loadTemplate(
      "js/templates/user.html",
      {
        "name" : json.data.name,
        "address" : json.data.address
    });
});
// area_userはテンプレートをはめ込む親divです。

JSONで変数を入れます。簡単です。

これだと上書きなので、追記モードの時はこんな感じ。

追記の時
$.getJSON('hoge.com',function(json){
    $("#area_user").loadTemplate(
      "js/templates/user.html",
      {
        "name" : json.data.name,
        "address" : json.data.address
      },
      {append:true}
   );
});

第3引数にappend:trueを入れることにより、#area_userへの追記モードになります。

思いがけず、結構いい感じにAJAX部分とテンプレート部分を切り離すことができました。
これでコードが少しキレイになります。

29
34
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
34