Webman은 기본적으로 PHP 원시 문법을 템플릿으로 사용하며, opcache를 활성화하면 최상의 성능을 발휘합니다. PHP 원시 템플릿 외에도 Webman은 Twig, Blade, think-template 템플릿 엔진을 제공합니다.

opcache 활성화

뷰를 사용할 때, PHP.ini에서 opcache.enableopcache.enable_cli 두 가지 옵션을 활성화하는 것이 좋습니다. 이렇게 하면 템플릿 엔진이 최상의 성능을 발휘합니다.

Twig 설치

  1. composer 설치

composer require twig/twig

  1. 구성 수정 config/view.php를 다음과 같이 변경합니다.
    
    <?php
    use support\view\Twig;

return [
'handler' => Twig::class
];

> **提示**
> 다른 구성 옵션은 options를 통해 전달합니다. 예를 들어

```php
return [
    'handler' => Twig::class,
    'options' => [
        'debug' => false,
        'charset' => 'utf-8'
    ]
];

Blade 설치

  1. composer 설치
composer require psr/container ^1.1.1 webman/blade
  1. 구성 수정 config/view.php를 다음과 같이 변경합니다.
    
    <?php
    use support\view\Blade;

return [
'handler' => Blade::class
];


## think-template 설치
1. composer 설치

`composer require topthink/think-template`

2. 구성 수정 `config/view.php`를 다음과 같이 변경합니다.
```php
<?php
use support\view\ThinkPHP;

return [
    'handler' => ThinkPHP::class,
];

提示
다른 구성 옵션은 options를 통해 전달합니다. 예를 들어

return [
    'handler' => ThinkPHP::class,
    'options' => [
        'view_suffix' => 'html',
        'tpl_begin' => '{',
        'tpl_end' => '}'
    ]
];

원시 PHP 템플릿 엔진 예제

app/controller/UserController.php 파일을 다음과 같이 생성합니다.

<?php
namespace app\controller;

use support\Request;

class UserController
{
    public function hello(Request $request)
    {
        return view('user/hello', ['name' => 'webman']);
    }
}

app/view/user/hello.html 파일을 다음과 같이 생성합니다.

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>webman</title>
</head>
<body>
hello <?=htmlspecialchars($name)?>
</body>
</html>

Twig 템플릿 엔진 예제

구성 수정 config/view.php를 다음과 같이 변경합니다.

<?php
use support\view\Twig;

return [
    'handler' => Twig::class
];

app/controller/UserController.php 파일을 다음과 같이 생성합니다.

<?php
namespace app\controller;

use support\Request;

class UserController
{
    public function hello(Request $request)
    {
        return view('user/hello', ['name' => 'webman']);
    }
}

app/view/user/hello.html 파일을 다음과 같이 생성합니다.

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>webman</title>
</head>
<body>
hello {{name}}
</body>
</html>

자세한 문서는 Twig 를 참고하세요.

Blade 템플릿 예제

구성 수정 config/view.php를 다음과 같이 변경합니다.

<?php
use support\view\Blade;

return [
    'handler' => Blade::class
];

app/controller/UserController.php 파일을 다음과 같이 생성합니다.

<?php
namespace app\controller;

use support\Request;

class UserController
{
    public function hello(Request $request)
    {
        return view('user/hello', ['name' => 'webman']);
    }
}

app/view/user/hello.blade.php 파일을 다음과 같이 생성합니다.

주의: Blade 템플릿의 접미사는 .blade.php 입니다.

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>webman</title>
</head>
<body>
hello {{$name}}
</body>
</html>

자세한 문서는 Blade를 참고하세요.

ThinkPHP 템플릿 예제

구성 수정 config/view.php를 다음과 같이 변경합니다.

<?php
use support\view\ThinkPHP;

return [
    'handler' => ThinkPHP::class
];

app/controller/UserController.php 파일을 다음과 같이 생성합니다.

<?php
namespace app\controller;

use support\Request;

class UserController
{
    public function hello(Request $request)
    {
        return view('user/hello', ['name' => 'webman']);
    }
}

app/view/user/hello.html 파일을 다음과 같이 생성합니다.

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>webman</title>
</head>
<body>
hello {$name}
</body>
</html>

자세한 문서는 think-template를 참고하세요.

템플릿 데이터 할당

view(템플릿, 변수 배열)을 사용하여 템플릿에 값을 할당하는 것 외에도, View::assign()을 호출하여 임의의 위치에서 템플릿에 값을 할당할 수 있습니다. 예를 들어:

<?php
namespace app\controller;

use support\Request;
use support\View;

class UserController
{
    public function hello(Request $request)
    {
        View::assign([
            'name1' => 'value1',
            'name2'=> 'value2',
        ]);
        View::assign('name3', 'value3');
        return view('user/test', ['name' => 'webman']);
    }
}

View::assign()은 특정 시나리오에서 매우 유용합니다. 예를 들어, 어떤 시스템에서 각 페이지 머리말에 현재 로그인 사용자의 정보를 표시해야 할 때, 매번 view('템플릿', ['user_info' => '사용자 정보']);로 이 정보를 할당하는 것은 매우 번거롭습니다. 해결책은 미들웨어에서 사용자 정보를 얻은 후 View::assign()을 사용하여 사용자 정보를 템플릿에 할당하는 것입니다.

뷰 파일 경로에 대한 설명

컨트롤러

컨트롤러가 view('템플릿명',[]);을 호출할 때, 뷰 파일은 다음과 같은 규칙으로 검색됩니다:

  1. /로 시작하는 경우, 해당 경로에서 직접 뷰 파일을 검색합니다.
  2. /로 시작하지 않고 멀티앱이 아닌 경우, app/view/ 하위의 해당 뷰 파일을 사용합니다.
  3. /로 시작하지 않고 멀티앱인 경우, app/앱명/view/ 하위의 해당 뷰 파일을 사용합니다.
  4. 템플릿 매개변수를 전달하지 않는 경우, 자동으로 2, 3 규칙에 따라 템플릿 파일을 검색합니다.

예제:

<?php
namespace app\controller;

use support\Request;

class UserController
{
    public function hello(Request $request)
    {
        // return view('user/hello', ['name' => 'webman']);와 동일합니다.
        // return view('/app/view/user/hello', ['name' => 'webman']);와 동일합니다.
        return view(['name' => 'webman']);
    }
}

클로저 함수

클로저 함수에서 $request->app는 비어 있으며, 어떤 애플리케이션에도 속하지 않으므로 클로저 함수는 app/view/ 하위의 뷰 파일을 사용합니다. 예를 들어 config/route.php에서 라우트를 정의하는 경우

Route::any('/admin/user/get', function (Reqeust $reqeust) {
    return view('user', []);
});

app/view/user.html을 템플릿 파일로 사용합니다. (Blade 템플릿을 사용할 때 템플릿 파일은 app/view/user.blade.php입니다.)

지정 애플리케이션

멀티앱 모드에서 템플릿을 재사용할 수 있도록, view($template, $data, $app = null)는 세 번째 매개변수 $app를 제공하여 어떤 애플리케이션 디렉토리의 템플릿을 사용할지를 지정할 수 있습니다. 예를 들어 view('user', [], 'admin');app/admin/view/ 하위의 뷰 파일을 강제로 사용합니다.

템플릿 매개변수 생략

클래스 컨트롤러 안에서는 템플릿 매개변수를 생략할 수 있습니다. 예를 들어

<?php
namespace app\controller;

use support\Request;

class UserController
{
    public function hello(Request $request)
    {
        // return view('user/hello', ['name' => 'webman']);와 동일합니다.
        // return view('/app/view/user/hello', ['name' => 'webman']);와 동일합니다.
        return view(['name' => 'webman']);
    }
}

Twig 확장

구성 view.extension에 콜백을 주어 Twig 뷰 인스턴스를 확장할 수 있습니다. 예를 들어 config/view.php를 다음과 같이 작성합니다.

<?php
use support\view\Twig;
return [
    'handler' => Twig::class,
    'extension' => function (\Twig\Environment $twig) {
        $twig->addExtension(new your\namespace\YourExtension()); // Extension 추가
        $twig->addFilter(new \Twig\TwigFilter('rot13', 'str_rot13')); // Filter 추가
        $twig->addFunction(new \Twig\TwigFunction('function_name', function () {})); // 함수 추가
    }
];

Blade 확장

마찬가지로 구성 view.extension에 콜백을 주어 Blade 뷰 인스턴스를 확장할 수 있습니다. 예를 들어 config/view.php를 다음과 같이 작성합니다.

<?php
use support\view\Blade;
return [
    'handler' => Blade::class,
    'extension' => function (Jenssegers\Blade\Blade $blade) {
        // Blade에 지시어 추가
        $blade->directive('mydate', function ($timestamp) {
            return "<?php echo date('Y-m-d H:i:s', $timestamp); ?>";
        });
    }
];

Blade 컴포넌트 사용

Alert 컴포넌트를 추가해야 한다고 가정합니다.

새 파일 app/view/components/Alert.php 생성

<?php

namespace app\view\components;

use Illuminate\View\Component;

class Alert extends Component
{

    public function __construct()
    {

    }

    public function render()
    {
        return view('components/alert')->rawBody();
    }
}

새 파일 app/view/components/alert.blade.php 생성

<div>
    <b style="color: red">hello blade component</b>
</div>

/config/view.php는 다음과 비슷한 코드를 가집니다.

<?php
use support\view\Blade;
return [
    'handler' => Blade::class,
    'extension' => function (Jenssegers\Blade\Blade $blade) {
        $blade->component('alert', app\view\components\Alert::class);
    }
];

이에 따라 Blade 컴포넌트 Alert 설정이 완료되었으며, 템플릿에서 사용할 때는 다음과 같이 작성합니다.

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>webman</title>
</head>
<body>

<x-alert/>

</body>
</html>

think-template 확장

think-template은 view.options.taglib_pre_load를 사용하여 태그 라이브러리를 확장합니다. 예를 들어

<?php
use support\view\ThinkPHP;
return [
    'handler' => ThinkPHP::class,
    'options' => [
        'taglib_pre_load' => your\namspace\Taglib::class,
    ]
];

자세한 내용은 think-template 태그 확장을 참고하세요.