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 ディレクトリ内にテンプレートファイルを作成する: 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
セキュリティに関する注意:動的出力が適切にエスケープされたことを確認することが重要です。