我正在使用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 ...
是否有一個清潔的解決方案來實現這一目標?有沒有辦法動態生成變量的數量,賦予模板,在那裏?提前致謝!
我認爲有很多方法可以做你想做的,但首先,你需要告訴我們什麼是更精確。也許你可以渲染diffies模板,不管你是否有類別。也許你可以檢查你的樹枝模板的價值$ newcommer,然後顯示你想要的。更具體的你的目標是什麼 – copndz