I'l*_*ack 0 php refactoring laravel laravel-blade laravel-5.4
我觉得这段代码看起来有点乱,逻辑是显示一个链接<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>
Run Code Online (Sandbox Code Playgroud)
如果有一种减少条件和使用循环的方法会很好.
为什么不呢:
<li class="{{ $active == 'sign_in'? 'active':'' }}">
@if ($active != 'sign_in')
<a href="{{ url_secure('sign_in') }}">Sign In</a>
@else
Sign In
@endif
</li>
Run Code Online (Sandbox Code Playgroud)
还不清楚为什么你检查$showLink是否设置为previoulsy.
好的,因为我已经阅读了你的评论,我使用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
Run Code Online (Sandbox Code Playgroud)