我有这个表数据:
Name | Score | Remarks
john | 80 | pass
jane | 85 | pass
如何使它看起来像这样:
Name | Score | Remarks
john | 80 | pass
jane | 85 |
备注表头应创建2的行数,但我对如何使用twig模板实现了概率。以下是我的代码:
{% 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
答案 0 :(得分: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 %}
添加一个Twig扩展名:
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;
}
}
答案 1 :(得分:1)
尝试这样的事情:
{% if loop.index0 % 2 == 0 %}
<td class="text-center" rowspan="2">{{name.remarks}}</td>
{% endif %}
% 2
对应rowspan="2"