我使用Slim 3和Twig的最简单示例创建了一个项目。
文件夹结构如下:
- public
- index.php
- style.css
Run Code Online (Sandbox Code Playgroud)
中的应用代码index.php如下:
<?php
require 'vendor/autoload.php';
$app = new \Slim\App();
$container = $app->getContainer();
// Twig
$container['view'] = function ($container) {
$view = new \Slim\Views\Twig('src/views', [
'cache' => false // TODO
]);
// Instantiate and add Slim specific extension
$basePath = rtrim(str_ireplace('index.php', '', $container['request']->getUri()->getBasePath()), '/');
$view->addExtension(new Slim\Views\TwigExtension($container['router'], $basePath));
return $view;
};
$app->get('/', function ($request, $response, $args) {
return $this->view->render($response, 'index/index.html.twig');
})->setName('index');
$app->run();
Run Code Online (Sandbox Code Playgroud)
现在的问题是,尝试加载时/style.css显示的是首页(index/index.html.twig)。为什么我无法访问该style.css文件?
我使用的服务器是PHP内置开发服务器,使用以下命令:
php -S localhost:8000 -t public public/index.php
如何加载资产?这里有什么问题?
原因是PHP内置的开发服务器“笨拙”。
我必须将此检查作为index.php文件中的第一件事。
// To help the built-in PHP dev server, check if the request was actually for
// something which should probably be served as a static file
if (PHP_SAPI == 'cli-server') {
$url = parse_url($_SERVER['REQUEST_URI']);
$file = __DIR__ . $url['path'];
if (is_file($file)) return false;
}
Run Code Online (Sandbox Code Playgroud)
来源:https : //github.com/slimphp/Slim-Skeleton/blob/master/public/index.php