简体   繁体   中英

Laravel Blade templating conditional formatting

I'm new to Laravel/MVC in general, so sorry if this is a stupid question. I'm migrating a legacy procedural app and am trying to echo separate database rows (fetched through an Eloquent model) for "Title, City, State, Country" as comma separated values.

The Blade template I have now currently looks like this, which is functional but hideous.

@foreach ($projects as $projects) 
{{ $projects->title}}{{ $projects->city? ', '.$projects->city : ""}}{{ $projects->state?  ', '.$projects->state : "" }}{{ $projects->country? ', '.$projects->country : "" }}
@endforeach

Is there a better way to do this? the legacy procedural code pushes it to an array and implodes it like below, but if I did do an array push/implode I'm not too sure whether it belongs in the Eloquent model or controller.

$tempArray = array();
if($row["city"]) array_push($tempArray, convert_text($row["city"]));
if($row["state"]) array_push($tempArray, convert_text($row["state"]));
if($row["country"]) array_push($tempArray, convert_text($row["country"]));
echo implode(", ", $tempArray);
echo (count($tempArray) > 0)?", ":"";

Well.. this should work:

@foreach ($projects as $project) 
    {{ implode(', ', array_filter([$project->city, $project->state, $project->country])) }}
@endforeach

Update: $project->attributes is protected, so I adjusted the code above to $project->getAttributes() .

Update 2: I missed the point of excluding the attributes that have an empty string, so I added array_filter() to the code above to filter out the ones that have a "falsy" value (such as an empty string, or null ).

Update 3: Realized that you want the attributes in a specific order.. and also realized that the code could be a lot simpler, so removed the array_only() and $project->getAttributes() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM