Riot.js(v3.6.0)でtableタグと格闘したmemo。

仕事でRiot.js、家ではReactというjavascriptにまみれてます。
Riot.jsのカスタムタグを使ってHTMLに動的な表示を実現させる稼業で今後も使いそうなのでmemo.

HTML側ではデータを元にtableを使ってこんな感じに表示させたい。 f:id:pdo99:20170712184938p:plain

至って普通のテーブルですが、左端のrowspanがちょっと工夫のいるところ。

Riot.jsを組み込む前のHTML

<table> 
      <thead> 
          <tr> 
              <th>会場</th> 
              <th>時間</th> 
              <th>研修会名</th> 
              <th>担当者</th> 
          </tr> 
      </thead> 
      <tbody> 
          <tr> 
              <td rowspan="2">****</th> 
              <td class="time">10:00~</td> 
              <td class="work"><a href="#">****</a></td> 
              <td class="name">****</td> 
         </tr> 
         <tr> 
             <td class="time">10:00~</td> 
             <td class="work"><a href="#">****</a></td> 
             <td class="name">****</td> 
        </tr> 
        <tr> 
            <td rowspan="1">¥¥¥¥</th> 
            <td class="time">10:00~</td> 
            <td class="work"><a href="#">¥¥¥¥</a></td> 
            <td class="name">¥¥¥¥</td>
        </tr>
    </tbody>
</table> 

だいたいデザイナさんからこんな感じのHTMLがもらえます。

Riot.js組み込み

表示するデータは会場単位のobjectの中にイベントの詳細が入っている形を作ります。 Javascriptで配列内の要素をキーに分割するmemo

<table class="training"> 
    <thead> 
        <tr> 
            <th>会場</th> 
            <th>時間</th> 
            <th>研修会名</th> 
            <th>担当者</th> 
        </tr> 
    </thead> 
    <tbody each={ schedule, key in schedules }> 
        <tr each={ val,i in schedule }> 
            <td if={ i < 1 } rowspan={ schedule.length }>{ key }</td> 
            <td class="time">{ val.time}~</td> 
            <td class="work"><a href="/hoge.html?hoge={ val.id }">{ val.displayName }</a></td> 
            <td class="name">{ val.staff }</td> 
        </tr> 
    </tbody> 
</table> 

会場単位のループをtbodyで行って、その中でイベント詳細のループをさらに回すという感じ。 rowspanはループカウントiで判定して表示を制御した。

参考

qiita.com

qiita.com