Laravel8で3項演算子を使ってCSSを切り替える方法

2734 回閲覧されました
みなさんこんにちは、jonioです。
LaravelのBladeの中のあるHTMLに対してページによって背景色を変えるなどCSSの切り替えをしたい時が場合によって出てきますが今回はそれを実現する方法の説明をします。
3項演算子
if文みたいなやつです。
if文だと↓の様にコードを分割します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php if(条件):?> | |
条件が成立している時の内容 | |
<?php else:?> | |
条件が成立しない時の内容 | |
<?php endif;?> |
しかし3項演算子を使うと1箇所にまとめて書く事ができます。
どういう事か分からないと思うので実際にコードを見てみます。
コードの書き方
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
A ? B : C |
Aが真ならBになってAが真ではないならCになるという意味です。
if文で言う所の「Aが真ならBになって」がif文が成り立つ場合で「Aが真ではないならCになる」がelseの場合です。
実際に使ってみます。
使用例
↓のコードで考えます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<a href="{{route('home')}}" class="list-group-item {{url()->current()==route('home')?'active':''}}"> |
「{{url()->current()==route(‘home’)?’active‘:”}}」の部分に3項演算子を使っています。
「url()->current()」は現在のurlという意味で「現在のURLがhomeならactiveクラスがついて現在のURLがhomeでないならクラスは何も付かない(”のこと)」という事です。