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

如何在Laravel中使用Blade创建动态博客布局?

嘿,我来帮你搞定这个交替布局的需求!你想用奇偶判断的思路没问题,但用循环的迭代次数代替ID判断会更靠谱——毕竟帖子ID可能因为删除、新增操作出现断层,而循环的次数是连续的,不会出错。

Laravel的Blade模板自带了$loop变量,能轻松获取当前循环的状态,比如$loop->iteration(从1开始的迭代次数),用它来判断奇偶就完美适配你的需求。下面给你两种实现方案:

方案1:分结构输出(直观易读)

直接根据迭代次数的奇偶,分别渲染「图-文」和「文-图」的结构:

@foreach($posts as $post)
    <div class="row align-items-center mb-4">
        @if($loop->iteration % 2 == 1)
            <!-- 第1、3条:图片在前,内容在后 -->
            <div class="col-sm-6">
                <a href="/post/{{ $post->slug }}">
                    <img src="{{ Voyager::image($post->image) }}" class="img-fluid" style="width:100%">
                </a>
            </div>
            <div class="col-sm-6">
                <a href="/post/{{ $post->slug }}" class="text-decoration-none">
                    <h3>{{ $post->title }}</h3>
                    <p>{{ Str::limit($post->content, 150) }}</p> <!-- 截取内容作为预览,长度可调整 -->
                </a>
            </div>
        @else
            <!-- 第2条:内容在前,图片在后 -->
            <div class="col-sm-6">
                <a href="/post/{{ $post->slug }}" class="text-decoration-none">
                    <h3>{{ $post->title }}</h3>
                    <p>{{ Str::limit($post->content, 150) }}</p>
                </a>
            </div>
            <div class="col-sm-6">
                <a href="/post/{{ $post->slug }}">
                    <img src="{{ Voyager::image($post->image) }}" class="img-fluid" style="width:100%">
                </a>
            </div>
        @endif
    </div>
@endforeach

方案2:用CSS反转布局(简洁高效)

如果不想写重复的HTML结构,可以利用Bootstrap的flex-row-reverse类,在偶数项时反转行内元素的顺序,代码更精简:

@foreach($posts as $post)
    <!-- 偶数项添加flex-row-reverse,实现布局反转 -->
    <div class="row align-items-center mb-4 {{ $loop->iteration % 2 == 0 ? 'flex-row-reverse' : '' }}">
        <div class="col-sm-6">
            <a href="/post/{{ $post->slug }}">
                <img src="{{ Voyager::image($post->image) }}" class="img-fluid" style="width:100%">
            </a>
        </div>
        <div class="col-sm-6">
            <a href="/post/{{ $post->slug }}" class="text-decoration-none">
                <h3>{{ $post->title }}</h3>
                <p>{{ Str::limit($post->content, 150) }}</p>
            </a>
        </div>
    </div>
@endforeach

额外小提示

  1. 你的路由代码里orderBy('created_at')默认是升序(旧帖在前),如果想显示最新的帖子,记得改成:
    $posts = App\Post::take(3)->orderBy('created_at', 'desc')->get();
    
  2. 建议用img-fluid代替img-responsive,这是Bootstrap 4+的标准类,适配性更好;
  3. 如果帖子有单独的摘要字段(比如excerpt),可以把$post->content换成$post->excerpt,预览内容会更精准。

这样就能完美实现你想要的「图-文 → 文-图 → 图-文」交替布局啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:04:29