View

7/8/2021

# Description:

  • Register Service tại ViewServiceProvider.php

  • Mặc định sử dụng twig template engine.

    public $bindings = [
        ViewFactory::class => TwigFactory::class,
    ];
    
    1
    2
    3

    → Nếu muốn thay đổi engine chỉ cần binding ViewFactory cho 1 class khác vd: BladeFactory, SmartyFactory,..

# Config:

# app.yml

view:
    dir_loader: src/templates
1
2
3
4

# Usage:

  • Type-hinting tại controller contructor:

    <?php
    
    namespace Nin\Controllers;
    
    use Nin\Libs\View\ViewFactory;
    
    class FooController
    {
        protected ViewFactory $view;
    
        public function __construct(ViewFactory $view)
        {
            $this->view = $view;
        }
    
        public function indexAction()
        {
            $foo = [
                ['name' => 'A'],
                ['name' => 'B'],
                ['name' => 'C'],
            ];
            return $this->view->make('index', ['foo' => $foo]);
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    // src/templates/index.html.twig
    
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Twig Example</title>
    </head>
    <body>
    
        <ul>
        {% for item in foo %}
            <li>{{ item.name }}</li>
        {% endfor %}
        </ul>
    
    </body>
    </html>
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
  • Facade:

    use Nin\Libs\Facades\View;
    
    $foo = [
        ['name' => 'A'],
        ['name' => 'B'],
        ['name' => 'C']
    ];
    return View::make('index', ['foo' => $foo]);
    
    1
    2
    3
    4
    5
    6
    7
    8

Packagist: https://packagist.org/packages/nin/nin (opens new window)