Laravel Blade简单的foreach包括$loop->first

huangapple go评论57阅读模式
英文:

Laravel Blade simple foreach including $loop->first

问题

我有一个表单,在其中显示了四个文本字段输入。当前的 app()->getLocale() 输入显示在左侧,下面的代码是用于显示在右侧的其他三个语言环境:

@foreach(['ca','en','es','nl'] as $lang)

    @if(app()->getLocale() == $lang) @continue @endif

    <li>
        <a href="#{{ $lang }}" class="@if($loop->first) active @endif">
    </li>

@endforeach

这些都是菜单选项卡,它们是隐藏的,只有第一个应该显示为活动状态,因此:

@if($loop->first) active @endif

然而,问题是,当当前的语言环境是 ca 时,$loop->first 也将是 ca。这个不能是活动的,因为它永远不会显示在右侧。

我正在尝试找到一个简单的解决方法,而不需要太多的 if else 条件。此外,数组 [‘ca’,‘en’,‘es’,‘nl’] 将根据来自 config 的一些数据更改,因此以后会有更多的语言环境,ca 将不总是第一个。所以我不能使用 @if(app()->getLocale() == ‘ca’) 进行检查,因为这也将在将来更改。

英文:

I have a form where I display four text field inputs. The current app()-&gt;getLocale() input is displayed on the left, and the below code is for the remaining 3 locales which are displayed on the right:

@foreach([&#39;ca&#39;,&#39;en&#39;,&#39;es&#39;,&#39;nl&#39;] as $lang)

    @if(app()-&gt;getLocale() == $lang) @continue @endif

    &lt;li&gt;
        &lt;a href=&quot;#{{ $lang }}&quot; class=&quot;@if($loop-&gt;first) active @endif&quot;
    &lt;/li&gt;

@endforeach

These are all menu tabs that are hidden, only the first one should be displayed as active, hence:

@if($loop-&gt;first) active @endif

The problem however is, that when the current locale is ca, also the $loop-&gt;first() will be ca. And this one cannot be the active one, since it will never be displayed on the right side.

I am trying to find an easy fix without too many if else things. Also, the array [&#39;ca&#39;,&#39;en&#39;,&#39;es&#39;,&#39;nl&#39;] will be changed for some data that comes from the config, so there will be more locales later and ca will not always be the first one. So I cannot do checks with @if(app()-&gt;getLocale() == &#39;ca&#39;) since that will change in the future as well.

答案1

得分: 5

替换为:

array_diff(['ca','en','es','nl'], [app()->getLocale()])

并移除此部分代码:

@if(app()->getLocale() == $lang) @continue @endif

这将从你的数组中移除表示当前语言的项目。

英文:

Instead of:

[&#39;ca&#39;,&#39;en&#39;,&#39;es&#39;,&#39;nl&#39;]

with:

array_diff([&#39;ca&#39;,&#39;en&#39;,&#39;es&#39;,&#39;nl&#39;], [app()-&gt;getLocale()])

and remove this:

@if(app()-&gt;getLocale() == $lang) @continue @endif

This will remove the item representing the current language from your array.

huangapple
  • 本文由 发表于 2023年1月9日 03:50:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75050806.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定