我正在使用 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 ...
有没有更清洁的解决方案来实现这一目标?没有办法动态生成给定模板的变量计数,是吗?提前致谢!