簡體   English   中英

未定義的屬性-Symfony2

[英]Undefined property - Symfony2

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

有沒有更清潔的解決方案來實現這一目標? 沒有一種方法可以動態生成分配給模板的變量計數,是否存在? 提前致謝!

這里是一個簡單的解決方案(如果我理解您的問題):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM