首页 > 解决方案 > 表头中的标题不应在 laravel 的 foreach 循环中重复

问题描述

我的观点

<table class="table">
  @foreach($students as $student)
    <thead>
      <tr style="background-color: #e9e5e4;">
        <td colspan="4">{{$student->teacher_name}}</td>
      </tr>
      <tr>
        <th> Name </th>
        <th> class</th>
        <th> subject </th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td> {{$student->name }}</td>
        <td> {{$student->class}} </td>
        <td> {{$student->subject }} </td>
      </tr>
    </tbody>
    @endforeach
  </table>

即使教师姓名相同,它也会向我显示多个表,我只想在更改教师姓名时创建新表,否则在同一个表中显示所有记录

标签: htmllaravelforeach

解决方案


试试下面的方法:

<table class="table">
  <thead>
  <tr>
    <th>Name</th>
    <th>Class</th>
    <th>Subject</th>
  </tr>
  </thead>
  <tbody>
  @foreach($students as $student)
    <tr style="background-color: #e9e5e4;">
      <td colspan="4">{{$student->teacher_name}}</td>
    </tr>
    <tr>
      <td>{{$student->name }}</td>
      <td>{{$student->class}} </td>
      <td>{{$student->subject }} </td>
    </tr>
  @endforeach
  </tbody>
</table>

或者

<table class="table">
  <thead>
  <tr>
    <th>Name</th>
    <th>Class</th>
    <th>Subject</th>
    <th>Teacher</th>
  </tr>
  </thead>
  <tbody>
  @foreach($students as $student)
    <tr>
      <td>{{$student->name }}</td>
      <td>{{$student->class}} </td>
      <td>{{$student->subject }} </td>
      <td style="background-color: #e9e5e4;">{{$student->teacher_name}}</td>
    </tr>
  @endforeach
  </tbody>
</table>

推荐阅读