Подвиды (макеты, шаблоны) в фреймворке Slim php - PullRequest
13 голосов
/ 11 августа 2011

Я пробую Slim php framework

Возможно ли иметь макеты или вложенные виды в Slim? Я хотел бы использовать файл представления в качестве шаблона с переменными в качестве заполнителей для других представлений, загружаемых отдельно.

Как бы я это сделал?

Ответы [ 7 ]

22 голосов
/ 29 октября 2011

имя файла: myview.php

<?php
class myview extends Slim_View
{
    static protected $_layout = NULL;
    public static function set_layout($layout=NULL)
    {
        self::$_layout = $layout;
    }
    public function render( $template ) {
        extract($this->data);
        $templatePath = $this->getTemplatesDirectory() . '/' . ltrim($template, '/');
        if ( !file_exists($templatePath) ) {
            throw new RuntimeException('View cannot render template `' . $templatePath . '`. Template does not exist.');
        }
        ob_start();
        require $templatePath;
        $html = ob_get_clean();
        return $this->_render_layout($html);
    }
    public function _render_layout($_html)
    {
        if(self::$_layout !== NULL)
        {
            $layout_path = $this->getTemplatesDirectory() . '/' . ltrim(self::$_layout, '/');
            if ( !file_exists($layout_path) ) {
                throw new RuntimeException('View cannot render layout `' . $layout_path . '`. Layout does not exist.');
            }
            ob_start();
            require $layout_path;
            $_html = ob_get_clean();
        }
        return $_html;
    }

}
?>

пример index.php:

<?php
require 'Slim/Slim.php';
require 'myview.php';

// instantiate my custom view
$myview = new myview();

// seems you need to specify during construction
$app = new Slim(array('view' => $myview));

// specify the a default layout
myview::set_layout('default_layout.php');

$app->get('/', function() use ($app) {
    // you can override the layout for a particular route
    // myview::set_layout('index_layout.php');
    $app->render('index.php',array());
});

$app->run();
?>

default_layout.php:

<html>
    <head>
        <title>My Title</title>
    </head>
    <body>
        <!-- $_html contains the output from the view -->
        <?= $_html ?>
    </body>
</html>
8 голосов
/ 05 сентября 2011

Тонкий каркас использует другие движки шаблонов, такие как Twig или Smarty , поэтому, если вы выберете движок шаблонов, который разрешает подпредставления, он будет работать.Для получения дополнительной информации о шаблонах представления в Slim, отметьте здесь .

7 голосов
/ 07 апреля 2013

Я работаю с моим видом:

class View extends \Slim\View
{
    protected $layout;

    public function setLayout($layout)
    {
        $this->layout = $layout;
    }

    public function render($template)
    {
        if ($this->layout){
            $content =  parent::render($template);
            $this->setData(array('content' => $content));
            return parent::render($this->layout);
        } else {
            return parent::render($template);
        }
    }
}

Вы можете добавить какой-нибудь метод, например setLayoutData(..) или appendLayoutData(..)


Несколько минут назад:

class View extends \Slim\View
{

    /** @var string */
    protected $layout;

    /** @var array */
    protected $layoutData = array();

    /**
     * @param string $layout Pathname of layout script
     */
    public function setLayout($layout)
    {
        $this->layout = $layout;
    }

    /**
     * @param array $data
     * @throws \InvalidArgumentException
     */
    public function setLayoutData($data)
    {
        if (!is_array($data)) {
            throw new \InvalidArgumentException('Cannot append view data. Expected array argument.');
        }

        $this->layoutData = $data;
    }

    /**
     * @param array $data
     * @throws \InvalidArgumentException
     */
    public function appendLayoutData($data)
    {
        if (!is_array($data)) {
            throw new \InvalidArgumentException('Cannot append view data. Expected array argument.');
        }

        $this->layoutData = array_merge($this->layoutData, $data);
    }

    /**
     * Render template
     *
     * @param  string $template Pathname of template file relative to templates directory
     * @return string
     */
    public function render($template)
    {
        if ($this->layout){
            $content = parent::render($template);

            $this->appendLayoutData(array('content' => $content));
            $this->data = $this->layoutData;

            $template = $this->layout;
            $this->layout = null; // allows correct partial render in view, like "<?php echo $this->render('path to parial view script'); ?>"

            return parent::render($template);;
        } else {
            return parent::render($template);
        }
    }
}
4 голосов
/ 11 мая 2016

С Slim 3

namespace Slim;
use Psr\Http\Message\ResponseInterface;

class View extends Views\PhpRenderer
{
    protected $layout;

    public function setLayout($layout)
    {
        $this->layout = $layout;
    }

    public function render(ResponseInterface $response, $template, array $data = [])
    {
        if ($this->layout){
            $viewOutput = $this->fetch($template, $data);
            $layoutOutput = $this->fetch($this->layout, array('content' => $viewOutput));
            $response->getBody()->write($layoutOutput);
        } else {
            $output = parent::render($response, $template, $data);
            $response->getBody()->write($output);
        }
        return $response;
    }
}

В макете:

<?=$data['content'];?>
1 голос
/ 31 марта 2014

Вы можете использовать это в родительском представлении:

$app = \Slim\Slim::getInstance();
$app->render('subview.php');
0 голосов
/ 29 мая 2017

Да, это возможно.Если вы не хотите использовать какой-либо шаблонизатор, такой как smarty или twig.Если вы хотите использовать только .php просмотр файла.Выполните следующие действия.

Шаг 1. Создайте новый каталог в корневом каталоге вашего проекта.например, шаблоны.

Шаг 2. Откройте файл dependencies.php и вставьте следующий код

$container = $sh_app->getContainer();

$container['view'] = function ($c) {
   $view = new Slim\Views\PhpRenderer('src/templates/');
   return $view;
};

Шаг 3. В методе вашего контроллера для рендеринга код представления должен выглядеть следующим образом.

$this->container->view->render($response,'students/index.php',['students' => $data]);
0 голосов
/ 29 октября 2014

Если вы хотите записать вывод в переменную, это так же просто, как использовать метод представления fetch():

//assuming $app is an instance of \Slim\Slim
$app->view()->fetch( 'my_template.php', array( 'key' => $value ) );
...