未定义的属性 - Symfony2

时间:2013-05-31 12:07:19

标签: php symfony undefined

我正在使用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 ...

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

1 个答案:

答案 0 :(得分:1)

这是一个简单的解决方案(如果我理解你的问题):

$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
    ));
}

如果您想要一个更清晰的解决方案来管理您的模板,您可以使用注释@Template()(您只需要返回一个数组以传递给视图):

// ...

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
            );
        }
    }
}