简体   繁体   English

Laravel Blade模板条件格式

[英]Laravel Blade templating conditional formatting

I'm new to Laravel/MVC in general, so sorry if this is a stupid question. 我一般来说是Laravel / MVC的新手,如果这是一个愚蠢的问题,非常抱歉。 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. 我正在迁移旧的程序应用程序,并试图以逗号分隔的值回显“标题,城市,州,国家/地区”的单独的数据库行(通过Eloquent模型获取)。

The Blade template I have now currently looks like this, which is functional but hideous. 我现在拥有的Blade模板看起来像这样,虽然功能正常但很丑陋。

@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. 遗留的过程代码将其推入数组并像下面那样进行内推,但是如果我确实进行了数组推入/内推,则我不太确定它是否属于Eloquent模型或控制器。

$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() . 更新: $project->attributes受保护,因此我将上面的代码调整为$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 ). 更新2:我错过了排除具有空字符串的属性的意义,因此我在上面的代码中添加了array_filter()来过滤出具有“假”值的属性(例如,空字符串或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() . 更新3:意识到您想要按特定顺序array_only()属性。并且还意识到代码可能要简单得多,因此删除了array_only()$project->getAttributes() array_only() $project->getAttributes()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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