Foreach 在节点内容中上传的图像:获取 url
Foreach image uploaded in a Node Content : get the url
我刚开始使用 Drupal 8,我想在我创建的内容中获取 url 的照片来显示它们。
上下文是:一张照片为客户上传图片。该客户可以在页面上看到它。为了共享这些数据,我创建了一个带有 id 的拍摄内容。
我所做的是:
$photos = $shooting->field_shooting_photos->target_id;
这让我可以获取上传的每张图片的 ID。现在我想在我的 .module 中对 $photos 执行一个 foreach,它将 return 每个 url 数组中的一个。
然后我将在我的 Twig 中使用这个数组并对它做一个 foreach return 每张照片。
我只是不知道该怎么做,我想我将不得不使用类似的东西
$path = $photo_id->getFileUri();
但我无法弄清楚将其放入数组的语法。
感谢您的帮助!
如果只有fid,需要加载文件。
use \Drupal\file\Entity\File;
$fid = 123; // Your fid
$file = File::load($fid);
从那里,您可以使用 getFileUri method to get the URI. If you want to get the complete URL, you can use the file_create_url 功能。
$uri = $file->getFileUri();
// You get : public://directory/file.jpg
$url = file_create_url($uri);
// You get : http://mywebsite.com/sites/default/files/directory/file.jpg
我刚开始使用 Drupal 8,我想在我创建的内容中获取 url 的照片来显示它们。
上下文是:一张照片为客户上传图片。该客户可以在页面上看到它。为了共享这些数据,我创建了一个带有 id 的拍摄内容。
我所做的是:
$photos = $shooting->field_shooting_photos->target_id;
这让我可以获取上传的每张图片的 ID。现在我想在我的 .module 中对 $photos 执行一个 foreach,它将 return 每个 url 数组中的一个。
然后我将在我的 Twig 中使用这个数组并对它做一个 foreach return 每张照片。
我只是不知道该怎么做,我想我将不得不使用类似的东西
$path = $photo_id->getFileUri();
但我无法弄清楚将其放入数组的语法。
感谢您的帮助!
如果只有fid,需要加载文件。
use \Drupal\file\Entity\File;
$fid = 123; // Your fid
$file = File::load($fid);
从那里,您可以使用 getFileUri method to get the URI. If you want to get the complete URL, you can use the file_create_url 功能。
$uri = $file->getFileUri();
// You get : public://directory/file.jpg
$url = file_create_url($uri);
// You get : http://mywebsite.com/sites/default/files/directory/file.jpg