2016-09-18 83 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)); 
});