如何在Slim Framework路由中呈现前端页面?

时间:2017-03-31 03:25:15

标签: php routes slim

我在我的文件夹中安装了Slim,我想知道是否可以从Slim路线渲染完整的html / css / js页面。

假设这是控制路线的文件:

rControl.php

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

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

$app = new \Slim\App;
$app->get('/myroute', function (Request $request, Response $response){

    /* I want to render the page when enter in this route*/ 

return $response;
});

$app->run();

并假设我有一个带css格式的自定义html文件:

myTemplate.html

<!DOCTYPE html>
<html lang="pt-br">
<head>

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>My title </title>
</head>

<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.min.css">

<script src="jquery-2.2.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/engine.js"></script>

<body>

<h1> Some text </h1>

<p> example text here </p>

<div> hi! more content... </div>

</body>
</html>

问题是:当用户转到&#34; / myroute&#34; myTemplate.html 页面的内容>吗

1 个答案:

答案 0 :(得分:2)

最简单的方法是使用PHP-View

<?php
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Views\PhpRenderer;

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

$app = new \Slim\App;
$container = $app->getContainer();
$container['renderer'] = new PhpRenderer("./templates");

$app->get('/myroute', function (Request $request, Response $response){
    return $this->renderer->render($response, "/myTemplate.html");
});

$app->run();

传统上,我们对模板使用.phtml扩展名来表示他们可以在其中包含PHP代码。您可以通过数组将数据作为第三个参数传递给模板文件{.1}}。