0

我正在使用 Symfony2。我的控制器找到了一些值——比如类别,由创建并将它们提供给模板。问题是,如果用户还没有创建任何类别,我想显示一条消息来邀请他创建类别。

这是代码:

    if($number_of_categories == 0){
        $newcommer = true;

        //Here the template doesn't need any variables, because it only displays
        // "Please first add some categories"
    } else {
        $newcommer = false;

        //Here the variables, which I give to the template 
        //are filled with meaningfull values
    }

return $this->render('AcmeBudgetTrackerBundle:Home:index.html.twig', array(
        'newcommer' => $newcommer,
        'expenses' => $expenses_for_current_month,
        'first_category' => $first_category,
        'sum_for_current_month' => $sum_for_current_month,
        'budget_for_current_month' => $budget_for_current_month
));

问题是如果用户没有类别我没有什么来填充变量,所以我必须写这样的东西:

        //What I want to avoid is this: 
        $expenses_for_current_month = null;
        $first_category = null;
        $sum_for_current_month = null;
        $budget_for_current_month = null;

只是为了避免Notice: Undefined variable ...

有没有更清洁的解决方案来实现这一目标?没有办法动态生成给定模板的变量计数,是吗?提前致谢!

4

1 回答 1

1

Here a simple solution (if I understood your problem) :

$template = 'AcmeBudgetTrackerBundle:Home:index.html.twig';

if ($number_of_categories == 0){

    //Here the template doesn't need any variables, because it only displays
    // "Please first add some categories"

    return $this->render($template, array(
        'newcommer' => true,
    ));

} else {

    //Here the variables, which I give to the template 
    //are filled with meaningfull values

    return $this->render($template, array(
        'newcommer' => false,
        'expenses' => $expenses_for_current_month,
        'first_category' => $first_category,
        'sum_for_current_month' => $sum_for_current_month,
        'budget_for_current_month' => $budget_for_current_month
    ));
}

And if you want a cleaner solution to manage your Template, you cna use the annotation @Template() (You just have to return an array to pass to the view) :

// ...

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class MyController extends Controller
{
    /**
     * @Route("/my_route.html")
     * @Template("AcmeBudgetTrackerBundle:Home:index.html.twig")
     */
    public function indexAction()
    {
            // ...

        if ($number_of_categories == 0){

            return array(
                'newcommer' => true,
            );

        } else {

            //Here the variables, which I give to the template 
            //are filled with meaningfull values

            return array(
                'newcommer' => false,
                'expenses' => $expenses_for_current_month,
                'first_category' => $first_category,
                'sum_for_current_month' => $sum_for_current_month,
                'budget_for_current_month' => $budget_for_current_month
            );
        }
    }
}
于 2013-05-31T12:28:59.707 回答