PHP 範本

slim/php-view 組件

PHP-View PHP 組件有助於您呈現 PHP 範本。

安裝

composer require slim/php-view

使用方式

您可以像這樣與 Slim 搭配使用

<?php

use Slim\Factory\AppFactory;
use Slim\Views\PhpRenderer;

require __DIR__ . '/../vendor/autoload.php';

// Create App
$app = AppFactory::create();

$app->get('/hello', function ($request, $response) {
    $renderer = new PhpRenderer(__DIR__ . '/../templates');
    
    $viewData = [
        'name' => 'John',
    ];
    
    return $renderer->render($response, 'hello.php', $viewData);
})->setName('profile');

$app->run();

在專案根目錄建立一個目錄:templates/

在範本目錄中建立一個範本檔案:templates/hello.php

範本內容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Slim Example</title>
</head>
<body>
    <h1>Hello, <?= htmlspecialchars($name, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?></h1>
</body>
</html>

輸出

Hello John

安全性注意事項:務必確保動態輸出已適當跳脫

了解更多資訊