Search code examples
phptwitter-bootstraproutesslim

How to server static file in slim framework without any extra middleware


Went through slim documentation and not able to find how to load css and js files.

URL routing is happening for css and js also and its not going to template folder

$app = new \Slim\Slim([
        'debug' => true,
        'templates.path' => 'templates/'
    ]);


Solution

  • For the case that configuring the webserver to serve these files is not an option (e.g. when the asset is selected dynamically), there is a bit of support in Slim:

    $app->get('/favicon.ico', function (Request $request, Response $response, array $args) {
        $streamFactory = new Slim\Psr7\Factory\StreamFactory();
        return $response->withBody(
            $streamFactory->createStreamFromFile(__DIR__ . '/favicon.ico')
        );
    });
    

    This code is specifically coded against Slim's PSR7 package. A more general approach would be to retrieve Psr\Http\Message\StreamFactoryInterface from the dependency injection (DI) container.