2013-05-31 37 views
0

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

是否有一個清潔的解決方案來實現這一目標?有沒有辦法動態生成變量的數量,賦予模板,在那裏?提前致謝!

+0

我認爲有很多方法可以做你想做的,但首先,你需要告訴我們什麼是更精確。也許你可以渲染diffies模板,不管你是否有類別。也許你可以檢查你的樹枝模板的價值$ newcommer,然後顯示你想要的。更具體的你的目標是什麼 – copndz

回答

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

謝謝!我沒有想到! – Faery