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

Laravel视图MaterializeCSS布局适配及@if语法错误排查

看起来你在Laravel Blade视图里用Materialize做布局时踩了语法坑,这个Parse error十有八九是Blade指令用错了——毕竟Blade有自己的一套条件判断语法,不能直接写原生PHP的elseif哦。

先给你解决问题的正确代码,再拆解错误原因:

正确的Blade布局实现

根据你的需求,我们可以把文章数量的判断和Materialize的列类结合起来,两种写法供你选择:

写法1:提前计算列类(视图更整洁)

@php
    // 先获取文章总数
    $totalPosts = count($posts);
    // 默认是超过2篇的4列布局
    $columnClass = 'col s12 m4';
    
    if($totalPosts === 1) {
        $columnClass = 'col s12 m6 offset-m3';
    } elseif($totalPosts === 2) {
        $columnClass = 'col s12 m6';
    }
@endphp

@foreach($posts as $post)
    <div class="{{ $columnClass }}">
        <!-- 这里放你的文章内容 -->
        <h3>{{ $post->title }}</h3>
        <p>{{ $post->content }}</p>
    </div>
@endforeach

写法2:直接在HTML类中使用Blade指令

@php
    $totalPosts = count($posts);
@endphp

@foreach($posts as $post)
    <div class="col s12
        @if($totalPosts === 1)
            m6 offset-m3
        @elseif($totalPosts === 2)
            m6
        @else
            m4
        @endif">
        <!-- 文章内容 -->
        <h3>{{ $post->title }}</h3>
        <p>{{ $post->content }}</p>
    </div>
@endforeach

为什么会触发语法错误?

你之前的代码大概率犯了这个核心错误:在Blade的@if后面直接写了原生PHP的elseif,而非Blade专属的@elseif指令。比如错误写法可能是这样的:

@if(count($posts) === 1)
    <div class="col s12 m6 offset-m3">
elseif(count($posts) === 2) <!-- 这里少了@,Blade无法识别! -->
    <div class="col s12 m6">
@else
    <div class="col s12 m4">
@endif

Blade的条件判断必须用@if、@elseif、@else、@endif这套完整指令,缺一不可,否则PHP解析器就会抛出语法错误。另外如果要在Blade里写原生PHP代码,必须用@php和@endphp包裹,不然也会触发语法问题。

这样写出来的布局完全符合你的需求:1篇文章居中占6列,2篇文章各占6列并排,超过2篇则各占4列,同时兼顾移动端响应式(移动端自动全屏显示)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:19:00