我试图写一个if-else循环:如果在数据库中保存了一个嵌入,它应该显示一个日历,如果不是,它应该显示一个按钮说"添加新日历/添加新嵌入",但它没有用。我无法弄清楚原因。当数据库中保存了嵌入时,它会显示嵌入,但是,如果没有嵌入,则不会显示添加新日历/嵌入的按钮:
刀片视图:
@if (empty($calendars))
@else
<h4>No calendar settings</h4><br>
<a href="{{ route('calendarsettings.create')}}">
<button class="btn btn-success btn-cons m-b-10" type="button">
<i class="fa fa-cloud-upload"></i>
<span class="bold">Add embed</span>
</button>
</a>
@endif
@foreach($calendars as $calendar)
{{ $calendar->embed }}
@endforeach
控制器:
public function kalendarz() {
$calendars = Calendar::with('users')->where('user_id', Auth::user()->id)->get();
return view('kalendarz',['calendars'=>$calendars]);
}
答案 0 :(得分:1)
正确的语法是:
func fetchObjects<Entity: NSManagedObject>(type: Entity.Type,
predicate: NSPredicate? = nil,
sortDescriptors: [NSSortDescriptor]? = nil,
fetchLimit: Int? = nil) throws -> [Entity] {
/*
NOTE: This fetch request is constructed this way, because there is a compiler error
when using type.fetchRequest() or Entity.fetchRequest() only in the test target, which
makes the fetchRequest initialize to nil and crashes the fetch at runtime.
*/
let name = String(describing: type)
let fetchRequest: NSFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: name)
答案 1 :(得分:0)
empty()
函数清空变量$calendars
,因此请尝试使用count()
@if(count($calendars) > 0)
<h4>No calendar settings</h4></br>
<a href="{{ route('calendarsettings.create')}}">
<button class="btn btn-success btn-cons m-b-10" type="button"><i class="fa fa-cloud-upload"></i> <span class="bold">Add embed</span></button>
</a>
@else
@foreach($calendars as $calendar)
{{ $calendar->embed }}
@endforeach
@endif
答案 2 :(得分:0)
使用Eloquent
从数据库获取结果时,您会获得Illuminate\Database\Eloquent\Collection
的实例。要检查该集合是否为空,请使用$collection->isEmpty()
或$collection->isNotEmpty()
(L5.4)。
@if ($calendars->isNotEmpty())
// Have entries.
@else
<h4>No calendar settings</h4></br>
<a href="{{ route('calendarsettings.create')}}"><button class="btn btn-success btn-cons m-b-10" type="button"><i class="fa fa-cloud-upload"></i> <span class="bold">Add embed</span>
</button></a>
@endif
@foreach($calendars as $calendar)
{{$calendar->embed}}
@endforeach
答案 3 :(得分:0)
在Laravel 5.4中,除非满足条件,否则我可能会使用@unless
blade指令来显示块。下面的代码实现的是&#34;如果我们有一些,则显示条目,并显示按钮,除非我们有一些条目&#34;。
@if($calendar)
// show entries
@endif
@unless(empty($calendars))
// show a button to add a new one
@endunless
它有点相同&#34;逻辑&#34;和其他人一样,不过我认为它比@else
语句更清晰易读,并且与if分开。