LoginSignup
6
4

More than 5 years have passed since last update.

JsRender での for と props の違い

Last updated at Posted at 2014-04-02

JsRender のメモ。

■目的(こんな感じで出力する)
user list

名前 年齢 一番好きな本
太郎 30歳 title - ONE PIECE
author - 尾田 栄一郎
花子 20歳 title - 日経新聞の数字がわかる本
author - 小宮 一慶

■データ構造

var data = {
  "title" : "user list",
  "users" : [
    {
      "name": "太郎",
      "age": "30",
      "favoriteBook": {
        "title" : "ONE PIECE",
        "author" : "尾田 栄一郎"
      }
    },
    {
      "name": "花子",
      "age": "20",
      "favoriteBook": {
        "title" : "日経新聞の数字がわかる本",
        "author" : "小宮 一慶"
      }
    }
  ]
};

■テンプレート

<script id="users" type="text/x-jsrender">
     {{if users.length > 0}}
          {{:title}}
          <table border="1">
               <tr>
                    <th>名前</th>
                    <th>年齢</th>
                    <th>一番好きな本</th>
               </tr>
               {{for users}}
               <tr>
                    <td>{{:name}}</td>
                    <td>{{:age}}</td>
                    <td>
                         {{props favoriteBook}}
                             {{:key}} - {{:prop}}<br />
                         {{/props}}
                    </td>
               </tr>
               {{/for}}
          </table>
     {{/if}}
</script>

※この程度の出力なら for も props も要らないのでは?というツッコミはなしで…(;´Д`)

で、なにをメモしておきたいかというと、

  • for
  • props

の違いです。
for は配列の要素をループするけど、
props はオブジェクトの属性をループします。

上記の例で行くと、

  • users は配列で、その中に各ユーザ情報がある

    • 各ユーザの情報を取得するには for を使う
  • favoriteBook はオブジェクト

    • オブジェクトの各属性(キーと値)を表示するには props を使う

てな感じで使い分ける必要があるってことです。
まぁ、ドキュメントをよく見ればいいだけのことなんですけどね…(;´Д`)

なので、詳細は本家のドキュメントを参照すること。
http://www.jsviews.com/#jsrapi

6
4
2

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
6
4