我正在浏览这里提供的一些代码和项目http://fatfreeframework.com/development。我的目标是创建一个使用F3投射的轻量级MVC kickstarter。我知道它之前已经完成了,但是我正在将它作为一种学习练习,我希望最终可以从中获得一些有用的东西。
我现在遇到的最大绊脚石是布局的概念。我知道文档提到在模板中使用模板,但我很难在实践中实现它。最后,我希望有1或2个布局(默认布局,也许是模态弹出窗口的自定义布局等),然后将我的视图渲染包裹在这些布局中。我想要一个默认布局,然后能够覆盖需要自定义页面的几个页面的默认值。这是我一直在使用的代码:
// this is the handler for one of my routes, it's on a controller class called Index
public function index($f3, $params)
{
// this (or anything else) should get passed into the view
$f3->set('listOfItems',array("item1", "item2"));
// set the view
$f3->set('content', 'index.htm')
// render the layout
\Template::instance()->render('layout.htm');
}
不幸的是,我不断得到一个空白页面。我是否完全走错了方向,或者我走在正确的轨道上?有没有办法在某处设置默认布局,以便在被覆盖之前使用它?
答案 0 :(得分:2)
您可以使用默认布局创建基类。然后为每个控制器类扩展它。例如:
abstract class Layout {
protected $tpl='layout.htm';
function afterRoute($f3,$params) {
echo \Template::instance()->render($this->tpl);
}
}
然后:
class OneController extends Layout {
function index($f3,$params) {
$f3->set('listOfItems',...);
$f3->set('content','one/index.htm');
}
}
class AnotherController extends Layout {
protected $tpl='popup.htm';//override default layout here
function index($f3,$params) {
$f3->set('listOfItems',...);
$f3->set('content','another/index.htm');
}
}
在layout.htm中:
<body>
<div id="content">
<include href="{{@content}}" if="isset(@content)"/>
</div>
</body>
UI
文件夹的结构:
/ui
|-- layout.htm
|-- popup.htm
|-- one
|-- index.htm
|-- another
|-- index.htm
这只是您如何组织代码的一个示例。 F3足够松散,可以让你以多种方式组织它。
答案 1 :(得分:0)
I had exactly the same problem - set everything up as required, rendered the layout, and kept getting a blank page. Also when I checked the HTML source of the rendered page it was completely empty.
If you look closely however rendering the layout is not enough, you have to also print it using the echo
command. So rather than the following example which appears at first glance to be correct:
$f3->route('GET /',
function($f3) {
// Instantiates a View object
$view = new View;
// Render the page
$view->render('template/layout.php');
you actually need the last line to start with echo
:
echo $view->render('template/layout.php');
For more examples see:
Also for some reason (which I'm sure will become clear soon - I've only just started using the Fat Free Framework) you seem to also be able to render an .htm
file which contain embedded PHP (i.e. they don't have to have the .php
extension).