2017-08-30 62 views
1

一個行跨度我有這個表中的數據:枝條上創建循環

Name | Score | Remarks 
john | 80 | pass 
jane | 85 | pass 

如何使它看起來像這樣:

Name | Score | Remarks 
john | 80 | pass 
jane | 85 | 

備註表頭應該創造的2行跨度,但我有如何使用樹枝模板實施的概率。下面是我的代碼:

{% for name in names %} 
     <tr> 
      <td class="text-center">{{name.name}}</td> 
      <td class="text-center">{{name.score}}</td> 
      <td class="text-center" rowspan="2">{{name.remarks}}</td> 
     </tr> 
{% endfor %} 

這段代碼的輸出是:

Name | Score | Remarks | 
john | 80 | pass | 
jane | 85 |   | pass 

回答

1

嘗試是這樣的:

{% if loop.index0 % 2 == 0 %} 
    <td class="text-center" rowspan="2">{{name.remarks}}</td> 
{% endif %} 

% 2對應rowspan="2"

+0

非常感謝! – zluj

+0

不客氣,謝謝你的回覆:) – doydoy44

+0

我發佈了一個解決方案,可以處理任何數據(例如多於2個) – mykiwi

2

你可以這樣做這個:

{% for name in names %} 
    <tr> 
     <td class="text-center">{{name.name}}</td> 
     <td class="text-center">{{name.score}}</td> 
     {% set rowspan = new_rowspan(names, loop.index0, 'remarks') %} 
     {% if rowspan %} 
      <td class="text-center" rowspan="{{ rowspan }}">{{name.remarks}}</td> 
     {% endif %} 
    </tr> 
{% endfor %} 

,並添加一個枝杈伸展:

class YourTwigExtension extends Twig_Extension 
{ 
    public function getFunctions() 
    { 
     return array(
      new Twig_Function('new_rowspan', [$this, 'calculateRowspan']), 
     ); 
    } 

    public function calculateRowspan($names, $from, $column) 
    { 
     // check if previous column has the same value 
     if ($from > 0 && $names[$from - 1][$column] === $names[$from][$column]) { 
      return; 
     } 

     for ($to = $from + 1; isset($names[$to]) && $names[$to][$column] === $names[$from][$column]; $to++); 

     return $to - $from; 
    } 
} 
+0

謝謝!這將幫助我在未來:) – zluj