我需要在Symfony模板中提供一些指导。 我只想为一个控制器中的所有视图设置默认模板。而不是在每个视图页面中扩展模板。 请检查代码我现在使用的方式。
//Controller
class HomeController extends Controller
{
public static $title="Customised Title";
public function indexAction()
{
return $this->render('homeBundle:Home:index.html.php',array('name'=>'test','title'=>self::$title));
}
public function aboutAction()
{
//$this->view->extend('homeBundle:Templates:default.html.php');
return $this->render('homeBundle:Home:about.html.php',array('name'=>'test','title'=>self::$title));
}
}
模板
视图/模板/ default.html.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php $view['slots']->output('title', isset($title)?$title:"Symfony Default Title") ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link href="<?php echo $view['assets']->getUrl('bundles/home/css/style.css') ?>" rel="stylesheet">
<link href="<?php echo $view['assets']->getUrl('bundles/home/css/bootstrap-responsive.css') ?>" rel="stylesheet">
</head>
<body>
<?php $view['slots']->output('_content') ?></body>
</html>
浏览 /views/Home/about.html.php
<?php $view->extend('homeBundle:Templates:default.html.php') ?>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sagittis vulputate urna.
/views/Home/index.html.php
<?php $view->extend('homeBundle:Templates:default.html.php') ?>
<?php
echo "hello ".$name;
?>
在上面的视图代码中,我们扩展了homeBundle:模板:每个视图的default.html.php。是否可以将它放在控制器中(可能在构造函数中)?
感谢Vbee的帮助。实际上我期待像视图不应该扩展的东西。 index.html.php应该只有它的内容。像
<?php
echo "hello ".$name;
?>
我们可以像使用静态varialbe一样使用静态变量而不是创建渲染方法。
class HomeController extends Controller
{
public static $title="Customised Title";
public static $template="homeBundle:Templates:default.html.php";
public function testAction()
{
return $this->render('homeBundle:Home:about.html.php',array('extend_view'=>self::$template,'name'=>'test','title'=>self::$title));
}
}
但是我想在控制器端完全呈现模板,在视图中应该只有动作视图内容。
答案 0 :(得分:0)
在控制器中创建自己的渲染方法:
<?php
//Controller
class HomeController extends Controller
{
public static $title="Customised Title";
public function testAction()
{
return $this->renderWithExtend('homeBundle:Home:about.html.php', array('name' => 'test', 'title' => self::$title));
}
public function renderWithExtend($route, $params)
{
return $this->render($route, array_merge(array('extend_view', 'homeBundle:Templates:default.html.php'), $params));
}
}
然后在你看来:
// index.html.php
<?php $view->extend($extend_view) ?>
<?php
echo "hello ".$name;
?>