fiddlestacks
fiddlestacks

Reputation: 109

Serving dynamic assets with Slim and Twig

I am trying to link images without using the extension because it makes it much easier for me to maintain all my client files.

assets/images/client should resolve to assets/images/client.png when the browser renders the page.

In Slim, it is thinking these are routes and not processing the image. Is there any way to eliminate anything with /assets from processing through Slim and have it just go through the regular http request?

Upvotes: 0

Views: 573

Answers (1)

Georgy Ivanov
Georgy Ivanov

Reputation: 1579

Consider returning those images using Slim, it retains control in your hands: you can change the route or containing folder anytime you wish. Also you can set additional headers e.g. for caching.

$app->get('/assets/images/{pathToClientImage}', function($request, $response, $args) {
    $pathToFile = $args['pathToClientImage'];
    $containingFolder = '../clients_images/'; // the actual folder where files are stored
    // since you want to omit file extension in the url, we'll have to find the file
    $matches = glob($containingFolder.$fileName.'.*');
    if ($matches) {
        $clientImagePath = array_shift($matches); // let's grab the first file matching our mask
        $clientImage = @file_get_contents($clientImagePath);
        $finfo = new \Finfo(FILEINFO_MIME_TYPE);
        $response->write($clientImage);
        return $response->withHeader('Content-Type', $finfo->buffer($clientImage));
    } else {
        // if no matches found, throw exception that will be handled by Slim
        throw new \Slim\Exception\NotFoundException($request, $response);
    }
});

In case URLs like assets/images/client.png (having file extension) is acceptable for you, you can do this in a simpler way:

$app->get('/assets/images/{pathToClientImage}', function($request, $response, $args) {
    $pathToFile = $args['pathToClientImage'];
    $path = '../clients_images/'.$fileName;
    $image = @file_get_contents($path);
    $finfo = new \Finfo(FILEINFO_MIME_TYPE);
    $response->write($image);
    return $response->withHeader('Content-Type', $finfo->buffer($image));
});

Upvotes: 1

Related Questions