在哪里设置 Zend2 Partial View 的数据? [英] Where to set Zend2 Partial View's data?

查看:53
本文介绍了在哪里设置 Zend2 Partial View 的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个视图显示为:

Let's pretend I have a view being shown as:

<?php 
    echo $this->partial( 'site/testimonials/partial.phtml', array() ); 
?>
<?php

假设我有一个名为推荐"的表,此视图的目的是仅在另一个视图上显示数据库中的最新推荐.

Let's say I have a table called "testimonials" and the purpose of this view is to only show the most recent testimonial in the database on another view.

在此过程中,我将指定数据必须来自何处?我是将它传递给 $this->partial,还是有更好更正确的方法将 db 查询逻辑放在局部视图中?这是一个视图,所以没有任何逻辑与之相关,但是我如何为其分配一个推荐模型",并让它在显示此视图时自动从数据库中获取数据?

Where during this process will I specify where the data must come from? Do I pass it in to $this->partial, or is there a better and more correct way to place the db query logic in the partial view? It's a view, so no logic is tied to it, but how then would I assign a "testimonial model" to it, and have it automatically grab the data from the db when displaying this view?

简短

如果我想避免将变量(例如最新的推荐 ID)传递给部分视图,我应该将获取最新推荐的逻辑放在哪里?

Where do I place the logic to get the latest testimonial, if I want to avoid passing variables (such as the latest testimonial ID) to the partial view?

推荐答案

对于此类任务,我认为最好使用视图助手.

For such tasks i think it is better to make view helper.

Module.php 类中:

<?php

use Zend\View\Model\ViewModel;

public function getViewHelperConfig()
{
    return array(
        'most_recent_testimonials' => function($helperPluginManager){
            $serviceLocator = $helperPluginManager->getServiceLocator();

            $view = new ViewModel();
            $view->setTerminal(true);
            $view->setTemplate('site/testimonials/partial.phtml');

            /*
             * There you may get all data you need using $serviceLocator
             */

            // inject data into template
            $view->setVariables(array(
                ...
            );

            // render template
            $template_rendered =
                $serviceLocator ->get('viewrenderer')
                ->render($view);

            return $template_rendered;
        }
    );
}

内部视图:

<?php echo $this->most_recent_testimonials(); ?>

这篇关于在哪里设置 Zend2 Partial View 的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆