public function TwigExtension::drupalImage in Twig Tweak 8.2
Builds an image.
Parameters
mixed $property: A property to identify the image.
string $style: (optional) Image style.
array $attributes: (optional) Image attributes.
bool $responsive: (optional) Indicates that the provided image style is responsive.
bool $check_access: (optional) Indicates that access check is required.
Return value
array|null A render array to represent the image.
File
- src/
TwigExtension.php, line 772
Class
- TwigExtension
- Twig extension with some useful functions and filters.
Namespace
Drupal\twig_tweakCode
public function drupalImage($property, $style = NULL, array $attributes = [], $responsive = FALSE, $check_access = TRUE) {
// Determine property type by its value.
if (preg_match('/^\\d+$/', $property)) {
$property_type = 'fid';
}
elseif (Uuid::isValid($property)) {
$property_type = 'uuid';
}
else {
$property_type = 'uri';
}
$files = \Drupal::entityTypeManager()
->getStorage('file')
->loadByProperties([
$property_type => $property,
]);
// To avoid ambiguity render nothing unless exact one image has been found.
if (count($files) != 1) {
return;
}
$file = reset($files);
$access = $check_access ? $file
->access('view', NULL, TRUE) : AccessResult::allowed();
if (!$access
->isAllowed()) {
return;
}
$build = [
'#uri' => $file
->getFileUri(),
'#attributes' => $attributes,
];
if ($style) {
if ($responsive) {
$build['#type'] = 'responsive_image';
$build['#responsive_image_style_id'] = $style;
}
else {
$build['#theme'] = 'image_style';
$build['#style_name'] = $style;
}
}
else {
$build['#theme'] = 'image';
}
CacheableMetadata::createFromRenderArray($build)
->merge(CacheableMetadata::createFromObject($access))
->applyTo($build);
return $build;
}