![](/img/trans.png)
[英]How to restructure positions of product media or remove all images using product api in Shopware
[英]How to get images in the product list view with an API call in Shopware?
我正在開發一個單頁應用程序,它具有完全由客戶端呈現的前端 (React) 和 Shopware 在后台充當無頭 CMS。 因此,所有產品數據都將從 API 中提取,結帳也將使用 API 發送數據。
我的問題如下:
在嘗試呈現產品列表頁面時,我調用了文章端點,該端點返回了我所有產品的基本信息。 問題是我還需要渲染與每個產品關聯的主圖像,並且此列表不會公開來自附加到產品的媒體的任何數據。
我可以使用Media 端點獲取產品的媒體項,問題是這個需要一個 Media Id,而我無法從文章的列出表示中獲得。
所以現在我看到獲取圖像的唯一方法是首先調用獲取所有產品,然后遍歷它們並獲取每個產品的詳細信息,使用每個產品 ID 再次調用文章端點,然后當我有媒體 ID 時我遍歷這些並使用媒體端點獲取每個產品的圖像,因為這是唯一一個在響應中公開實際圖像路徑的圖像。 這似乎太復雜和緩慢了。
有沒有更聰明的方法來做到這一點? 我可以讓 Shopware 在文章列表響應中輸出與當前產品相關聯的第一個圖像的路徑嗎?
我還看到圖像的路徑如下所示: /media/image/f5/fb/95/03_200x200.jpg
到/media/image/的第一部分是固定的,這是直接的,我在媒體對象的文章詳細信息響應中獲得圖像的文件名和擴展名,甚至文件擴展名,在 API 的響應中看起來像這樣。
問題是我不知道f5/fb/95/代表什么。 如果我可以從詳細信息中獲取此信息,我可以以編程方式組合圖像的 URL,然后我就不需要調用媒體端點。
任何幫助是極大的贊賞。 提前致謝!
您可以在Shopware源代碼的\\ Shopware \\ Bundle \\ MediaBundle \\ Strategy \\ Md5Strategy類中查看如何生成路徑。 兩種相關方法是:
<?php
public function normalize($path)
{
// remove filesystem directories
$path = str_replace('//', '/', $path);
// remove everything before /media/...
preg_match("/.*((media\/(?:archive|image|music|pdf|temp|unknown|video|vector)(?:\/thumbnail)?).*\/((.+)\.(.+)))/", $path, $matches);
if (!empty($matches)) {
return $matches[2] . '/' . $matches[3];
}
return $path;
}
public function encode($path)
{
if (!$path || $this->isEncoded($path)) {
return $this->substringPath($path);
}
$path = $this->normalize($path);
$path = ltrim($path, '/');
$pathElements = explode('/', $path);
$pathInfo = pathinfo($path);
$md5hash = md5($path);
if (empty($pathInfo['extension'])) {
return '';
}
$realPath = array_slice(str_split($md5hash, 2), 0, 3);
$realPath = $pathElements[0] . '/' . $pathElements[1] . '/' . join('/', $realPath) . '/' . $pathInfo['basename'];
if (!$this->hasBlacklistParts($realPath)) {
return $realPath;
}
foreach ($this->blacklist as $key => $value) {
$realPath = str_replace($key, $value, $realPath);
}
return $realPath;
}
一步一步地,這通常發生在圖像路徑上,例如https://example.com/media/image/my_image.jpg
,將其傳遞給encode
-method:
normalize
方法會剝離除media/image/my_image.jpg
之外的所有內容
從結果字符串中生成md5-hash: 5dc18cdfa0...
步驟1的結果字符串在每個/
處分割: ['media', 'image', 'my_image.jpg']
md5-hash中的前三個字符對被存儲到一個數組中: ['5d', 'c1', '8c']
最終路徑是從步驟3和4的陣列中組裝出來的: media/image/5d/c1/8c/my_image.jpg
每次出現的/ad/
都會被/g0/
代替。 這樣做是因為有一些廣告攔截器可以攔截對包含/ad/
URL的請求
Shopware 會為您計算路徑。
沒有必要知道散列路徑......
您將被重定向到正確的路徑。
請嘗試以下操作:
/media/image/ + image['path'] + image['extension']
縮略圖的一個:
/media/image/thumbnail/ + image['path'] + '_200x200' + image['extension']
or
/media/image/thumbnail/ + image['path'] + '_600x600' + image['extension']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.