2017-03-10 13 views
0

を反復しながら、二回ROWSPAN使用して、私はフラスコを経由してJinja2のテンプレートに次のリストを渡している:Jinja2のフラスコ:

yrs = [2016, 2017] 
months = [['June'], ['January', 'February']] 
names = [[['John', 'Mike']], [['Sara'], ['Steph', 'James']]] 

私はこのようになりますテーブルを作成しようとしている:https://jsfiddle.net/46qqfef5/4/

ここで私はそれを実現するために一緒に入れている失敗したJinja2のコードは次のとおりです。

<div class="table-responsive"> 
    <table class="table table-bordered"> 
    <thead> 
     <tr> 
     <th>Year</th> 
     <th>Month</th> 
     <th>Name</th> 
     </tr> 
    </thead> 
    <tbody> 
     {% for yr_index in range(yrs | count) %} 
     {% for month_index in range(months[yr_index] | count) %} 
      {% for name_index in range(names[yr_index][month_index] | count) %} 
      <tr> 
       {% if loop.first %} 
       {% if loop.first %} 
        <td rowspan="{{ names[yr_index] | count }}">{{ yrs[yrs_index] }}</td> 
       {% endif %} 
       <td rowspan="{{ names[yr_index][month_index] | count }}">{{ months[yr_index][month_index] }}</td> 
       {% endif %} 
       <td>{{ names[yr_index][month_index][name_index] }}</td> 
      </tr> 
     {% endfor %} 
     {% endfor %} 
    </tbody> 
    </table> 
<div> 

だから私は基本的には組織的なテーブルにこれらのリストを解凍しようとしているが、私は持っていますrowspan属性で多くの問題が発生します。たとえPythonのリストの構造を変更する必要があるとしても、どんなヒントも高く評価されます。

答えて

1

これを最初に試してください(テストしませんでした)。 loop.firstを誤用しているようです(実際にはloop.firstに依存することはできません)。また、カウントを取得する前にnames[yr_index]リストをフラット化する必要もあります。

これを読むことを検討する:http://jinja.pocoo.org/docs/dev/tricks/#accessing-the-parent-loop

<div class="table-responsive"> 
    <table class="table table-bordered"> 
    <thead> 
     <tr> 
     <th>Year</th> 
     <th>Month</th> 
     <th>Name</th> 
     </tr> 
    </thead> 
    <tbody> 
     {% for yr in yrs %} 
     {% set yr_loop = loop %} 
     {% for month in months[loop.index0] %} 
      {% set month_loop = loop %} 
      {% for name in names[yr_loop.index0][loop.index0] %} 
      <tr> 
       {% if loop.first %} 
       {% if month_loop.first %} 
        <td rowspan="{{ names[yr_loop.index0]|sum(start=[])|count }}">{{ yr }}</td> 
       {% endif %} 
       <td rowspan="{{ loop.length }}">{{ month }}</td> 
       {% endif %} 
       <td>{{ name }}</td> 
      </tr> 
     {% endfor %} 
     {% endfor %} 
    </tbody> 
    </table> 
<div> 
+0

"UndefinedError: 'リストオブジェクト'に属性 '値'がありません。 1年あたりのアイテムの数え方を理解する必要があるように見えます。親ループにアクセスする際のヒント - うまくいくはずです! –

+0

@ jcmetz21 '.values()'を削除するだけです。私の間違い。 –

+0

完璧に動作します! –

関連する問題