Php 未定义的属性-Symfony2
我用的是Symfony2。我的控制器找到一些由创建的值(如类别),并将它们提供给模板。问题是,如果用户还没有创建任何类别,我想显示一个消息,邀请他创建类别 代码如下:Php 未定义的属性-Symfony2,php,symfony,undefined,Php,Symfony,Undefined,我用的是Symfony2。我的控制器找到一些由创建的值(如类别),并将它们提供给模板。问题是,如果用户还没有创建任何类别,我想显示一个消息,邀请他创建类别 代码如下: if($number_of_categories == 0){ $newcommer = true; //Here the template doesn't need any variables, because it only displays // "Please fi
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;
只是为了避免注意:未定义变量…
是否有更清洁的解决方案来实现这一点?没有一种方法可以动态生成给定给模板的变量计数,是吗?提前谢谢 这里有一个简单的解决方案(如果我理解你的问题):
如果您想要一个更干净的解决方案来管理模板,您可以使用注释(您只需返回一个数组来传递给视图):
我认为有很多方法可以满足你的需求,但首先,你需要更准确地告诉我们。无论是否有类别,都可以渲染“衍射”模板。也许你可以在你的小枝模板中签入$newcommer的值,然后显示你想要的。更具体地说你的目标是什么谢谢你!我还没想到呢!
$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
));
}
// ...
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
);
}
}
}