无脂肪PHP布局


Fat Free PHP Layouts

我正在浏览这里提供的一些代码和项目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');
}

不幸的是,我一直收到一张空白页。我是朝着完全错误的方向前进,还是走在正确的轨道上?有没有办法在某个地方设置默认布局,以便在被覆盖之前一直使用它?

您可以创建一个具有默认布局的基类。然后对每个控制器类进行扩展。例如:

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');
  }
}

在布局.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足够松散,可以用多种方式组织它。

我遇到了完全相同的问题——根据需要设置所有内容,呈现布局,并不断获得空白页面。此外,当我检查渲染页面的HTML源代码时,它是完全空的。

如果仔细观察,但渲染布局还不够,则还必须使用echo命令打印。因此,与其说下面的例子乍一看是正确的:

$f3->route('GET /',
    function($f3) {
        // Instantiates a View object
        $view = new View;
        // Render the page
        $view->render('template/layout.php');

您实际上需要最后一行以echo:开头

        echo $view->render('template/layout.php');

有关更多示例,请参阅:

  • http://fatfreeframework.com/views-and-templates
  • https://www.digitalocean.com/community/tutorials/how-to-use-the-fat-free-php-framework
  • http://takacsmark.com/fat-free-php-framework-tutorial-4-database-models-crud/

此外,出于某种原因(我相信很快就会清楚——我刚刚开始使用Fat Free Framework),您似乎也能够呈现包含嵌入式PHP的.htm文件(即,它们不必具有.php扩展名)。

相关文章: