Code Monkey home page Code Monkey logo

yiisoft-yii-view's Introduction

Yii View Extension


Latest Stable Version Total Downloads Build status Scrutinizer Code Quality Code Coverage Mutation testing badge static analysis type-coverage

The package is an extension of the Yii View Rendering Library. It adds WEB-specific functionality and compatibility with PSR-7 interfaces.

Requirements

  • PHP 7.4 or higher.

Installation

The package could be installed with composer:

composer require yiisoft/yii-view --prefer-dist

General usage

There are two ways to render a view:

  • Return an instance of the Yiisoft\DataResponse\DataResponse class with deferred rendering.
  • Render immediately and return the rendered result as a string.

Rendering result as a PSR-7 response

The Yiisoft\DataResponse\DataResponse class is an implementation of the Psr\Http\Message\ResponseInterface. For more information about this class, see the yiisoft/data-response package. You can get an instance of a response with deferred rendering as follows:

/**
 * @var \Yiisoft\Aliases\Aliases $aliases
 * @var \Yiisoft\DataResponse\DataResponseFactoryInterface $dataResponseFactory
 * @var \Yiisoft\View\WebView $webView
 */

$viewRenderer = new \Yiisoft\Yii\View\ViewRenderer(
    $dataResponseFactory,
    $aliases,
    $webView,
    '/path/to/views', // Full path to the directory of view templates or its alias.
    'layouts/main', // Default is null, which means not to use a layout.
);

// Rendering a view with a layout.
$response = $viewRenderer->render('site/page', [
    'parameter-name' => 'parameter-value',
]);

The rendering will be performed directly when calling getBody() or getData() methods of the Yiisoft\DataResponse\DataResponse. If a layout is set, but you need to render a view without the layout, you can use an immutable setter withLayout():

$viewRenderer = $viewRenderer->withLayout(null);

// Rendering a view without a layout.
$response = $viewRenderer->render('site/page', [
    'parameter-name' => 'parameter-value',
]);

Or use renderPartial() method, which will call withLayout(null):

// Rendering a view without a layout.
$response = $viewRenderer->renderPartial('site/page', [
    'parameter-name' => 'parameter-value',
]);

Rendering result as a string

To render immediately and return the rendering result as a string, use renderAsString() and renderPartialAsString() methods:

// Rendering a view with a layout.
$result = $viewRenderer->renderAsString('site/page', [
    'parameter-name' => 'parameter-value',
]);

// Rendering a view without a layout.
$result = $viewRenderer->renderPartialAsString('site/page', [
    'parameter-name' => 'parameter-value',
]);

Change view templates path

You can change view templates path in runtime as follows:

$viewRenderer = $viewRenderer->withViewPath('/new/path/to/views');

You can specify full path to the views directory or its alias. For more information about path aliases, see description of the yiisoft/aliases package.

Use in the controller

If the view renderer is used in a controller, you can either specify controller name explicitly using withControllerName() or determine name automatically by passing a controller instance to withController(). In this case the name is determined as follows:

App\Controller\FooBar\BazController -> foo-bar/baz
App\Controllers\FooBar\BazController -> foo-bar/baz
Path\To\File\BlogController -> blog

With this approach, you do not need to specify the directory name each time when rendering a view template:

use Psr\Http\Message\ResponseInterface;
use Yiisoft\Yii\View\ViewRenderer;

class SiteController
{
    private ViewRenderer $viewRenderer;

    public function __construct(ViewRenderer $viewRenderer)
    {
        // Specify the name of the controller:
        $this->viewRenderer = $viewRenderer->withControllerName('site');
        // or specify an instance of the controller:
        //$this->viewRenderer = $viewRenderer->withController($this);
    }

    public function index(): ResponseInterface
    {
        return $this->viewRenderer->render('index');
    }
    
    public function contact(): ResponseInterface
    {
        // Some actions.
        return $this->viewRenderer->render('contact', [
            'parameter-name' => 'parameter-value',
        ]);
    }
}

This is very convenient if there are many methods (actions) in the controller.

Injection of additional data to the views

In addition to parameters passed directly when rendering the view template, you can set extra parameters that will be available in all views. In order to do it you need a class implementing at least one of the injection interfaces:

use Yiisoft\Yii\View\CommonParametersInjectionInterface;
use Yiisoft\Yii\View\LayoutParametersInjectionInterface;

final class MyParametersInjection implements
    CommonParametersInjectionInterface,
    LayoutParametersInjectionInterface
{
    // Pass both to view template and to layout
    public function getCommonParameters(): array
    {
        return [
            'common-parameter-name' => 'common-parameter-value',
        ];
    }
    
    // Pass only to layout
    public function getLayoutParameters(): array
    {
        return [
            'layout-parameter-name' => 'layout-parameter-value',
        ];
    }
}

Link tags and meta tags should be organized in the same way.

use Yiisoft\Html\Html;
use Yiisoft\View\WebView;
use Yiisoft\Yii\View\LinkTagsInjectionInterface;
use Yiisoft\Yii\View\MetaTagsInjectionInterface;

final class MyTagsInjection implements
    LinkTagsInjectionInterface,
    MetaTagsInjectionInterface
{
    public function getLinkTags(): array
    {
        return [
            Html::link()->toCssFile('/main.css'),
            'favicon' => Html::link('/myicon.png', [
                'rel' => 'icon',
                'type' => 'image/png',
            ]),
            'themeCss' => [
                '__position' => WebView::POSITION_END,
                Html::link()->toCssFile('/theme.css'),
            ],
            'userCss' => [
                '__position' => WebView::POSITION_BEGIN,
                'rel' => 'stylesheet',
                'href' => '/user.css',
            ],
        ];
    }
    
    public function getMetaTags(): array
    {
        return [
            Html::meta()
                ->name('http-equiv')
                ->content('public'),
            'noindex' => Html::meta()
                ->name('robots')
                ->content('noindex'),
            [
                'name' => 'description',
                'content' => 'This website is about funny raccoons.',
            ],
            'keywords' => [
                'name' => 'keywords',
                'content' => 'yii,framework',
            ],
        ];
    }
}

You can pass instances of these classes as the sixth optional parameter to the constructor when creating a view renderer, or use the withInjections() and withAddedInjections methods.

$parameters = new MyParametersInjection();
$tags = new MyTagsInjection();

$viewRenderer = $viewRenderer->withInjections($parameters, $tags);
// Or append it:
$viewRenderer = $viewRenderer->withAddedInjections($parameters, $tags);

The parameters passed to render() method have more priority and will overwrite the injected content parameters if their names match.

Localize view file

You can set a specific locale that will be used to localize view files with withLocale() method:

$viewRenderer = $viewRenderer->withLocale('de_DE');

For more information about localization, see at the localization section in yiisoft/view package.

Testing

Unit testing

The package is tested with PHPUnit. To run tests:

./vendor/bin/phpunit

Mutation testing

The package tests are checked with Infection mutation framework with Infection Static Analysis Plugin. To run it:

./vendor/bin/roave-infection-static-analysis-plugin

Static analysis

The code is statically analyzed with Psalm. To run static analysis:

./vendor/bin/psalm

License

The Yii View Extension is free software. It is released under the terms of the BSD License. Please see LICENSE for more information.

Maintained by Yii Software.

Support the project

Open Collective

Follow updates

Official website Twitter Telegram Facebook Slack

yiisoft-yii-view's People

Contributors

samdark avatar vjik avatar devanych avatar terabytesoftw avatar thenotsoft avatar xepozz avatar roxblnfk avatar fantom409 avatar kamarton avatar rustamwin avatar sankaest avatar stylecibot avatar viktorprogger avatar dependabot[bot] avatar mj4444ru avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.