Php view render class

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

License

devanych/view-renderer

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Scrutinizer Code Coverage Scrutinizer Code Quality

A small and easy-to-use PHP library designed for rendering native PHP views.

  • Convenient flat block system.
  • Setting global parameters for all views.
  • Support for using existing PHP functions.
  • Easy extensibility by adding custom functions.
  • Flexible layout functionality with unlimited nesting.

A guide with a detailed description in Russian language is available here.

This package requires PHP version 7.4 or later.

composer require devanych/view-renderer 

The simplest example of rendering:

use Devanych\View\Renderer; $renderer = new Renderer('/path/to/root/directory/of/views'); $content = $renderer->render('path/to/view/file', [ 'variableName' => 'the value of a variable of any type', ]); echo $content;

The render() method takes as its first argument the path to the view file, which must be relative to the directory passed to the constructor when the object was created. The second argument passes an array of parameters ( name => value ) that will be converted to variables inside the view.

$renderer->render('post/show', [ 'post' => $posts->get($id), ]);

The view file can be with or without an extension, if the file extension is not specified, .php will be substituted by default. The default extension can be changed by passing it to the constructor as the second argument.

$renderer = new Renderer('/path/to/root/directory/of/views', 'tpl');

Within layouts and views, a renderer instance is available at $this .

$this->renderBlock('title');?>title>

The block() , beginBlock() , and endBlock() methods allow you to create content blocks in your view. The content of blocks is saved for use anywhere in the view, as well as in any parent layout. The method renderBlock() renders the stored content of the block.

DOCTYPE html> en"> UTF-8"> $this->renderBlock('title');?>title> $this->renderBlock('meta');?> head> body class pl-s">app"> $this->renderBlock('content');?> body> html>
 declare(strict_types=1); /** @var Devanych\View\Renderer $this */ $this->layout('layouts/main'); $this->block('title', 'Page Title'); ?> p>Page Contentp>  $this->beginBlock('meta');?> meta name pl-s">description" content pl-s">Page Description">  $this->endBlock();?>
> html lang pl-s">en"> head> meta charset pl-s">UTF-8"> title>Page Titletitle> meta name pl-s">description" content pl-s">Page Description"> head> body class pl-s">app"> p>Page Contentp> body> html>

Blocks can’t be nested, but you can render one block inside another.

Allowed -->  $this->beginBlock('parent');?> $this->renderBlock('children');?>  $this->endBlock();?>  $this->beginBlock('parent');?>  $this->beginBlock('children');?>  $this->endBlock();?>  $this->endBlock();?>

Note that content is a reserved block name. it renders the content of the view and child layouts. If you try to create a block named content , the \RuntimeException exception is thrown.

When calling the renderBlock() method with the name of a nonexistent block, the renderBlock() method returns an empty string, so no additional methods are needed to check the existence of the block. The second argument in renderBlock() can pass the default value, which will be substituted if the block with the specified name does not exist.

Output the block content, if it exists -->  if ($name = $this->renderBlock('name')): ?> h1>$name;?>h1>  endif;?> $this->renderBlock('title', 'Default Title');?> $this->renderBlock('title', $this->renderBlock('default-title'));?>

Layouts are a special type of representations that are very convenient to use for rendering repetitive parts (header, footer, sidebar, etc.). This package allows you to build layout chains with unlimited nesting. Layout inheritance is set in the file of the view or child layout by the layout() method.

Parent layout code ( layouts/main ):

DOCTYPE html> en"> UTF-8"> $this->renderBlock('title');?>title> head> body class pl-s">app"> $this->renderBlock('content');?> body> html>

Child layout code ( layouts/columns ):

 declare(strict_types=1); /** @var Devanych\View\Renderer $this */ $this->layout('layouts/main'); ?> main class pl-s">main"> $this->renderBlock('content');?> main> aside class pl-s">sidebar"> aside>
 declare(strict_types=1); /** @var Devanych\View\Renderer $this */ $this->layout('layouts/columns'); $this->block('title', 'Page Title'); ?> p>Page Contentp>
$renderer->render('site/page', [/* params */]);
> html lang pl-s">en"> head> meta charset pl-s">UTF-8"> title>Page Titletitle> head> body class pl-s">app"> main class pl-s">main"> p>Page Contentp> main> aside class pl-s">sidebar"> aside> body> html>

If you just need to render the child layout file from the parent layout, you can use the render() method.

DOCTYPE html> en"> UTF-8"> $this->renderBlock('title');?>title> head> body class pl-s">app"> $this->render('layouts/_header.php')?> $this->renderBlock('content');?> $this->render('layouts/_footer.php', [ 'parameter' => 'value' ])?> body> html>
> html lang pl-s">en"> head> meta charset pl-s">UTF-8"> title>Page Titletitle> head> body class pl-s">app"> header>Headerheader> p>Page Contentp> footer>Footerfooter> body> html>

The extension functionality allows you to add your own functions and use them inside layouts and views. To add a function, you need to create your own class that implements the Devanych\View\Extension\ExtensionInterface interface. The interface contains only one method that returns an array whose keys are the names of added functions, and the values can be any possible variants of the callable type.

interface ExtensionInterface < /** * Returns an array of functions as `function name` => `function callback`. * * @return array */ public function getFunctions(): array; >

This package contains a single extension Devanych\View\Extension\AssetExtension, which simplifies the connection of assets (scripts, styles, fonts, etc.) and adds a timestamp to the file. To add an extension, use the addExtension() method.

$extension = new AssetExtension('/path/to/assets', 'https://examle.com/assets', true); $renderer->addExtension($extension); // Result: 'https://examle.com/assets/css/style.css?v=1601742615' $renderer->asset('css/style.css');

Using the addGlobal() method, you can add global parameters that will be available in all views and layouts.

// The `$variableName` variable will now be available inside files. $renderer->addGlobal( 'variableName', 'the value of a variable of any type');

Adding a variable with the same name again will cause a \RuntimeException , but you can change the value of the global variable for a specific view by passing a parameter with the same name when rendering the view, or simply assigning it in the view itself.

// For all views and layouts, the value is `$author` will equal `Boby` $renderer->addGlobal( 'author', 'Boby'); // Only for the `blog/page` view, the value is `$author` will be equal to `John` $renderer->render('blog/page', [ 'author' => 'John', ]); // or assign a value in the view $author = 'John';

To prevent the output of potentially dangerous HTML code, the renderer contains the esc() method, which escapes special characters, converts them to the corresponding HTML entities.

// Result: '<script>alert(123);</script>' $renderer->esc(''); // Equivalently to: `htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8', true)`

This method is for convenience, but you can also use the original htmlspecialchars() function, as all existing PHP functions are available in views and layouts.

Источник

Разработка класса View в своем MVC фреймворке

Сейчас мы с вами сделаем класс View , который будет заниматься представлением данных. Он будет получать параметром объект класса Page , а своим результатом возвращать готовый HTML код страницы, который можно будет выводить на экран.

Посмотрим, как мы будем использовать класс View в файле index.php :

); $routes = require $_SERVER[‘DOCUMENT_ROOT’] . ‘/project/config/routes.php’; $track = ( new Router($routes) ) -> getTrack($_SERVER[‘REQUEST_URI’]); $page = ( new Dispatcher ) -> getPage($track); echo (new View) -> render($page); // вот так используем класс View ?>

Структура кода класса View будет иметь следующий вид:

renderLayout($page, $this->renderView($page)); > private function renderLayout(Page $page, $content) < >private function renderView(Page $page) < >> ?>

Метод renderView

Метод renderView будет получать файл представления и подставлять в него значения переменных. Это делается хитрым образом. Как вы знаете, переменные, которые используются в файле с представлением, содержатся в свойстве data объекта класса Page .

Эти переменные представляют собой ассоциативный массив. Нам нужно превратить этот массив в настоящие переменные, а затем подключить файл с представлением через include . В этом случае указанные доступные в этом файле переменные получат свое значение и на выходе мы получим просто HTML код уже с подставленными значениями переменных.

Для того, чтобы преобразовать массив в переменные, используем специальную функцию extract :

Метод renderLayout

Давайте теперь сделаем метод renderLayout . Этот метод будет брать файл лэйаута и подставлять в него значение переменных $title и $content (она будет передаваться параметром метода и будет представлять собой результат работы метода renderView ):

Итоговый код

Давайте соберем весь наш код вместе:

Разберите приведенный код класса View . Затем самостоятельно, не подсматривая в мой код, реализуйте такой же класс. Проверьте его работу.

Источник

Читайте также:  Java stream sort list
Оцените статью