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

Laravel Blade组件可选$description为空时隐藏对应p标签的最优方案

Laravel组件空description标签隐藏最优实现方案

核心逻辑:问题根源是Section title组件无论$description是否有有效值,都会固定渲染p标签,且Action section组件默认会给description插槽传入空字符串,导致空标签出现。最优方案是从组件渲染逻辑层面控制DOM输出,完全避免生成多余空节点,比CSS隐藏等方案性能更优、语义更友好。

1. 修改Section title组件代码

在组件内增加条件判断,仅当$description有实际有效值时才渲染对应的p标签,代码如下:

<div class="px-4 sm:px-6">
    <h2 class="text-lg font-medium leading-6 text-gray-900">
        {{ $title }}
    </h2>
    {{-- 仅当description不为空时渲染标签 --}}
    @if (trim($description ?? '') !== '')
    <p class="mt-1 text-sm text-gray-500">
        {{ $description }}
    </p>
    @endif
</div>

这里额外加trim判断是为了避免传入全空格的无效内容时,仍渲染无意义的空标签。

2. 优化Action section组件的插槽传值逻辑(可选但推荐)

去掉默认的空字符串回退逻辑,仅当$description存在时才传入对应插槽,进一步减少冗余输出:

<div {{ $attributes->merge(['class' => 'pt-6 bg-white border sm:rounded-md sm:overflow-hidden']) }}>
    <x-section-title>
        <x-slot name="title">{{ $title }}</x-slot>
        {{-- 仅当description参数存在时传入插槽 --}}
        @isset($description)
        <x-slot name="description">{{ $description }}</x-slot>
        @endisset
    </x-section-title>

    <div class="flex flex-col mt-6">
        <div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
            <div class="inline-block min-w-full py-2 align-middle sm:px-6 lg:px-8">
                {{ $content }}
            </div>
        </div>
    </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 17:45:00