英文:
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()->getLocale()
input is displayed on the left, and the below code is for the remaining 3 locales which are displayed on the right:
@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
These are all menu tabs that are hidden, only the first one should be displayed as active, hence:
@if($loop->first) active @endif
The problem however is, that when the current locale is ca
, also the $loop->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 ['ca','en','es','nl']
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()->getLocale() == 'ca')
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:
['ca','en','es','nl']
with:
array_diff(['ca','en','es','nl'], [app()->getLocale()])
and remove this:
@if(app()->getLocale() == $lang) @continue @endif
This will remove the item representing the current language from your array.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论