2016-09-18 52 views
0

我想链接图片而不使用扩展名,因为它使我更容易维护所有客户端文件。为Slim和Twig提供动态资源

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

在苗条,它认为这些是路线和不处理图像。有没有办法通过Slim处理/assets来消除任何东西,并让它只是通过常规的http请求?

+0

您需要将此与添加到您的'.htaccess'文件默认的配置文件夹请求将被发送到你的index.php – jmattheis

回答

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(有文件扩展名)是您可以接受的,你可以在一个更简单的方式做到这一点:

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