【问题标题】:Serving dynamic assets with Slim and Twig使用 Slim 和 Twig 提供动态资产
【发布时间】:2016-10-04 06:36:04
【问题描述】:

我正在尝试在不使用扩展程序的情况下链接图像,因为它使我更容易维护所有客户端文件。

assets/images/client 应该在浏览器呈现页面时解析为 assets/images/client.png

在 Slim 中,它认为这些是路线而不是处理图像。有什么办法可以消除通过 Slim 处理的 /assets 的任何内容,让它只通过常规的 http 请求?

【问题讨论】:

  • 您需要将此添加到您的.htaccess 文件中,默认配置文件夹请求将发送到您的 index.php

标签: image routing twig slim


【解决方案1】:

考虑使用 Slim 返回这些图像,它保留在您手中的控制权:您可以随时更改路线或包含文件夹。您还可以设置其他标题,例如用于缓存。

$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);
    }
});

如果您可以接受像 assets/images/client.png(具有文件扩展名)这样的 URL,您可以通过更简单的方式来执行此操作:

$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));
});

【讨论】:

    猜你喜欢
    • 2013-01-03
    • 1970-01-01
    • 2018-10-10
    • 2020-06-19
    • 2013-03-06
    • 2021-01-22
    • 1970-01-01
    • 2013-01-06
    • 2015-12-29
    相关资源
    最近更新 更多