检查视图模板中对象是否存在或为空 [英] Check if object exists or is empty in view template
问题描述
如何检查在视图模板中,如果结果对象包含任何条目?
How do you check within the view template if the result object contains any entries?
(有一个已经有类似的问题,但是这个问题略有不同)
(There was a similar question already, but this one is slightly different)
使用 CakePHP 3博客教程。它们显示了如何在一页上列出所有文章:
Take the CakePHP 3 blog tutorial for example. They show how to list all articles on one page:
// src/Controller/ArticlesController.php
public function index() {
$this->set('articles', $this->Articles->find('all'));
}
和视图模板:
<!-- File: src/Template/Articles/index.ctp -->
<table>
<tr>
<th>Id</th>
<th>Title</th>
</tr>
<?php foreach ($articles as $article): ?>
<tr>
<td><?= $article->id ?></td>
<td>
<?= $this->Html->link($article->title, ['action' => 'view', $article->id]) ?>
</td>
</tr>
<?php endforeach; ?>
</table>
缺点:如果数据库中没有条目,则HTML表是
Disadvantage: if there are no entries in the database the HTML table is still rendered.
如何防止这种情况并显示类似对不起,没有结果这样的简单信息?
How can I prevent this and show a simple message like "Sorry no results" insteat?
在 CakePHP 2
中我使用
if ( !empty($articles['0']['id']) ) {
// result table and foreach here
} else {
echo '<p>Sorry no results...</p>';
}
但由于 $ articles
现在是一个不再起作用的对象...是否有新的捷径来检查结果对象?还是您通常先使用另一个foreach,例如
But since $articles
is now an object this doesn't work anymore... Is there a new "short way" to check the result object? Or do you usally use another foreach first, like
$there_are_results = false;
foreach ($articles as $article) {
if ( !empty($article->id) ) {
$there_are_results = true;
break;
}
}
if ( $there_are_results == true ) {
// result table and second foreach here
} else {
echo '<p>Sorry no results...</p>';
}
感谢您的提示。
推荐答案
您可以使用 iterator_count()
函数来了解集合中是否有结果:
You can use the iterator_count()
function to know if there are results in the set:
if (iterator_count($articles)) {
....
}
您也可以使用收集方法来获取第一个元素:
You can also use the collection methods to get the first element:
if (collection($articles)->first()) {
}
编辑:
自CakePHP 3.0.5起,检查查询或结果集是否为空的最佳方法是
Since CakePHP 3.0.5 the best way to check for emptiness on a query or a result set is this:
if (!$articles->isEmpty()) {
...
}
这篇关于检查视图模板中对象是否存在或为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!