重构以在 blade 中显示或不显示 link

Refactor to show link or not in blade

我觉得这段代码看起来有点乱,逻辑是显示一个link <a href 否则只显示文本。

我如何重构它以使其看起来更干净且易于维护?

   <ol class="breadcrumb">
        <li class="{{ $active == 'sign_in'? 'active':'' }}">
            @if($active != 'sign_in')
                @php($showLink = true)
            @else
                @php($showLink = false)
            @endif

            @if($showLink)
                 <a href="{{ url_secure('sign_in') }}">
            @endif
                Sign In
            @if($showLink)
                </a>
            @endif
        </li>
        <li class="{{ $active == 'article'? 'active':'' }}"> 
            @if($active != 'article' && $showLink)
                @php($showLink= true)
            @else
                @php($showLink= false)
            @endif

            @if($showLink)
                 <a href="{{ url_secure('article')}}">
            @endif
                Articles
            @if($showLink)</a>@endif
        </li>

        <li> </li> //repeat the code logic like above
     </ol>

如果有办法减少if条件和使用循环就好了。

为什么不只是:

<li class="{{ $active == 'sign_in'? 'active':'' }}">
    @if ($active != 'sign_in')
        <a href="{{ url_secure('sign_in') }}">Sign In</a>
    @else
        Sign In
    @endif
</li>

另外,您为什么检查之前设置的 $showLink 也不清楚。

好的,我已经阅读了您的评论,我使用 foreach 循环对模板进行了一些修改:

@php
// some initial variables
$allowed_to_click = true;
// this is a link to selected page
$selected_link = 'something';
@endphp
@foreach ($links as $link)
    @php
    // check if this link is ACTIVE
    $active = $link == $selected_link;
    // check if we can CLICK this link
    $allowed_to_click = $active || $allowed_to_click;
    @endphp

    <li class="{{ $active ? 'active':'' }}">
    @if ($allowed_to_click)
        <a href="{{ url_secure('some_url')}}">Some Caption</a>
    @else
        Some Caption
    @endif
    </li>

    @php
    // if link is ACTIVE - following links are unclickable
    if ($active) {
        $allowed_to_click = false;
    }
    @endphp
@endforeach