eisteeee/sectioned-view

PHP原生模板中的布局继承和分区

v1.3 2015-03-17 12:55 UTC

This package is not auto-updated.

Last update: 2024-09-28 16:51:51 UTC


README

SectionedView实现了PHP原生模板中的布局继承和分区。它旨在简单且易于集成

##功能

  • 无缝集成到PHP原生模板(类似于 <?php ?>
  • 易于与框架(如Slim PHP)集成

入门

###安装

我建议您通过Composer安装SectionedView

composer.json

"require": {
  "eisteee/sectioned-view": "~1.0"
}

或者使用命令行

composer require eisteee/sectioned-view

###要求

仅需要 PHP >= 5.3.0

###快速教程

实例化一个SectionedView渲染器

$template_path = __DIR__ . "/templates"; //absolute path to your template directory
$view = new \SectionedView\View($template_path);
$view->render("hello.php", array('name' => 'World'));

templates/hello.php

Hello, <?= $name ?>!

渲染

Hello, World!

为了返回渲染内容而不是直接打印到输出,请使用

$template_path = __DIR__ . "/templates"; //absolute path to your template directory
$view = new \SectionedView\View($template_path, array('echo' => 'false'));
$view->render("hello.php", array('name' => 'World'));

###使用布局和分区

考虑到上面的相同设置,现在我们将使用一个布局文件

templates/layout.php

<?php use SectionedView\Section; ?>
<html>
<head>
   <title>Hello</title>
</head>
<body>
   <?php Section::output('content') ?>
</body>
</html>

templates/hello.php

<?php use SectionedView\Section; ?>
<?php Section::layout('layout.php') /* path relative to specified template_path in SectionedView */ ?>
<!-- the moment you specify a layout file any text that is not within a section gets ommited -->
<!-- you can only specify one layout per file -->
<?php Section::start('content') ?>
   Hello, <?= $name ?>!
<?php Section::end() ?>

将渲染

<html>
<head>
   <title>Hello</title>
</head>
<body>
   Hello, World!
</body>
</html>

###Slim PHP视图

可以为Slim PHP项目创建一个用于视图的类,如下所示

class SectionedSlimView extends \Slim\View
{
    private $sectionedView;
    public function __construct($template_base)
    {
        parent::__construct();
        $this->sectionedView = new \SectionedView\View($template_base);
    }

    public function render($template)
    {
        $this->sectionedView->render($template, $this->data->all());
    }
}

将其注册为您的Slim视图

$template_path = __DIR__ . "/templates"; /* path relative to specified template_path in SectionedView */
$app = new \Slim\Slim(array(
    "view" => new SectionedSlimView($template_path);
));

然后您就可以开始了