You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8 Blade模板如何实现每行展示2条食材记录

实现方案

利用Laravel Blade内置的$loop循环对象判断行的起止位置,不需要手动编写计数器,兼容Laravel 8所有版本,且能适配元素数量为奇数的场景,不会出现HTML标签未闭合的布局问题。

核心判断逻辑

  • 当循环到每一行的第一个元素(即列表的第1、3、5...个元素)时,提前输出带row类的容器开标签
  • 当循环到每一行的最后一个元素(即列表的第2、4、6...个元素),或者是整个列表的最后一个元素时,输出row容器的闭合标签

改造后的完整Blade代码

@foreach($productIngredients as $productIngredient)
    {{-- 行首判断:开启row容器 --}}
    @if($loop->first || $loop->iteration % 2 == 1)
    <div class="row g-3">
    @endif

    @php
        if($selectedProductIngredients->contains('ingredient_id', $productIngredient->id) === true){
            $item = \App\Models\SelectedProductIngredient::where('product_id', $product->id)->where('ingredient_id', $productIngredient->id)->first();
            $weight = $item->weight;
        } else {
            $weight = null;
        }
    @endphp

    <div class="col-6">
        <div class="form-check py-2">
            <input id="productIngredientId-{{ $productIngredient->id }}"
                   class="form-check-input enableInput" style="margin-top:10px"
                   name="productIngredient[]" type="checkbox"
                   value="{{ $productIngredient->id }}"
                   @if($selectedProductIngredients->contains('ingredient_id', $productIngredient->id) === true) checked @endif>
            <label class="form-check-label" for="flexCheckChecked">
                {{ $productIngredient->name }} [{{ $productIngredient->short_name }}]
            </label>
            <input id="productIngredient-{{ $productIngredient->id }}" type="text"
                   name="productIngredient-{{ $productIngredient->id }}" maxlength="10"
                   class="form-control weight-input weightMask"
                   style="width:100px;display: inline; margin-left:20px" placeholder=""
                   value="{{ $weight }}">
        </div>
    </div>

    {{-- 行尾判断:闭合row容器 --}}
    @if($loop->iteration % 2 == 0 || $loop->last)
    </div>
    @endif
@endforeach

注意事项

  • 代码中用到的$loop对象是Blade循环内置属性,$loop->iteration代表当前元素的序号(从1开始计数),$loop->first/$loop->last分别标记当前是否是列表的第一个/最后一个元素,不需要手动初始化计数器
  • 代码里的g-3是Bootstrap 5自带的栅格间距类,用于给两个并排的col-6元素添加合理间距,如果使用Bootstrap 4可以替换为no-gutters自行调整边距
  • 所有原有业务判断逻辑完全保留,不会修改现有可运行的功能逻辑
  • 就算列表总元素数为奇数(比如共5个配料,最后一行仅1个col-6元素),也会自动闭合row容器,不会产生无效的空标签

内容的提问来源于stack exchange,提问作者trilel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.24 18:06:09