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

Laravel Blade根据文章type字段动态引入不同include模板失效问题求解

问题修复方案

核心错误原因

  • 逻辑顺序错误:现有代码先判断集合的type属性再遍历整个集合,只要判断成立就会将全部10条内容渲染为对应类型的模板
  • 运算符使用错误:条件判断中误用赋值运算符=而非比较运算符===,赋值操作执行后会返回true,导致两个判断条件均生效,两次遍历整个集合,最终输出20条内容
  • 拼写错误:quote类型被错写为quotse,会导致类型匹配失效

修复后代码

调整逻辑为先遍历单篇文章,再针对单篇的type值加载对应模板:

@foreach($newsFirstLine as $article)
    @if($article->type === 'quote')
        @include("cards/quote", [
            'slug' => $article->getUrl(),
            'title' => $article->tr('title'),
            'avatar' => $article->image,
            'created' => $article->created_at->format('d.m.Y'),
            'createdHi' => $article->created_at->format('H:i'),
        ])
    @elseif($article->type === 'news')
        @include("cards/news", [
            'image' => $article->image,
            'slug' => $article->getUrl(),
            'title' => $article->tr('title'),
            'created' => $article->created_at->format('d.m.Y'),
            'createdHi' => $article->created_at->format('H:i'),
        ])
    @endif
@endforeach

可选优化方案

如果后续新增更多文章类型,可通过动态拼接模板名简化代码:

@foreach($newsFirstLine as $article)
    @include("cards/".$article->type, [
        'slug' => $article->getUrl(),
        'title' => $article->tr('title'),
        'created' => $article->created_at->format('d.m.Y'),
        'createdHi' => $article->created_at->format('H:i'),
        $article->type === 'quote' ? 'avatar' : 'image' => $article->image,
    ])
@endforeach

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:36:04