0

我正在使用 cakephp 2.4

在我的应用程序中,我有一个视图,CategoriesController即“社论”,我可以显示该类别下的所有文章http://mydomain/categories/editorial

我正在尝试显示 home.ctp 中“社论”类别下的所有文章echo $this->element('editorials');

但它显示Notice (8): Undefined variable: articles [APP\View\Elements\Editorials.ctp, line 4]

CategoriesController.php

public function Editorial() {
    $category =  $this->Category->find('first', array(
        'conditions' => array(
            'Category.id' => 1
        )
    ));

    $this->set(compact('category'));

    $this->Paginator = $this->Components->load('Paginator');

    $this->Paginator->settings = array(
        'Article' => array(
            'recursive' => -1,
            'contain' => array(
                'Category'
            ),
            'limit' => 5,
            'conditions' => array(
                'Article.category_id' => $category['Category']['id'],

            ),
            'order' => array(
                'Article.id' => 'ASC'
            ),
            'paramType' => 'querystring',
        )
    );
    $articles = $this->Paginator->paginate($this->Category->Article);

    $this->set(compact('articles'));

}

查看文件:

    <?php if (!empty($articles)): ?>

<?php echo $this->element('editorials'); ?>

<?php echo $this->element('pagination-counter'); ?>

<?php echo $this->element('pagination'); ?>

<?php endif; ?>

元素/社论.ctp:

    <div class="row">
<?php
$i = 0;
foreach ($articles as $art):
$i++;
if (($i % 4) == 0) { echo "\n<div class=\"row\">\n\n";}
?>
<div class="col col-sm-3">

<?php echo $this->Html->link($art['Article']['title'], array('controller' => 'articles', 'action' => 'view', 'id' => $art['Article']['id'])); ?>
<br />
</div>
<?php
if (($i % 4) == 0) { echo "\n</div>\n\n";}
endforeach;
?>

<br />
<br />

</div>
4

2 回答 2

0

尝试添加$this->render('file');您的编辑操作并用没有.ctp 的视图文件名替换文件

于 2013-11-14T11:04:14.713 回答
0

你可以改变的东西:

    1. In controller:
       $this->set(compact('category', 'articles')); // one set()

    2. In view: (Main Point)

      <?php echo $this->element('editorials', array('articles' => $articles)); ?>

在这里,您需要articles像上面一样将变量传递给元素,默认情况下元素无法识别viewVars.

于 2013-11-14T15:17:02.200 回答