脚本宝典收集整理的这篇文章主要介绍了cakephp-3.0 – 检查视图模板中是否存在对象或为空,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
(已经有一个similar question,但这个略有不同)
以CakePHP 3 blog tutorial为例.他们展示了如何在一个页面上列出所有文章:
// 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表.
如何防止这种情况并显示一条简单的消息,例如“抱歉没有结果”的内容?
在CakePHP 2中我使用过
if ( !empty($articles['0']['id']) ) { // result table and foreach here } else { echo '<p>Sorry no results...</p>'; }
但是因为$articles现在是一个对象,所以它不再起作用了…是否有新的“简短方法”来检查结果对象?或者你是否通常先使用另一个foreach,比如
$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>'; }
谢谢你的提示.
以上是脚本宝典为你收集整理的cakephp-3.0 – 检查视图模板中是否存在对象或为空全部内容,希望文章能够帮你解决cakephp-3.0 – 检查视图模板中是否存在对象或为空所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。