我会做另一种方式。在您的节点预处理功能中:
use Drupal\image\Entity\ImageStyle; // Don't forget this use.
function THEMENAME_preprocess_node__NODETYPE(&$variables){
$node = $variables['node'];
if(isset($node->get('field_image')->entity)){
$image_style = 'large'; // Or whatever your image style's machine name is.
$style = ImageStyle::load($style);
$variables['image'] = $style->buildUrl($node->get('field_image')->entity->getFileUri()); // Generates file url.
}
}
然后,在您的模板(node--NODETYPE.html.twig)中,以这种方式渲染图像:
{% if image %}
<img src="{{ image }}" />
{% endif %}
虽然,如果您不得不渲染大量图像,我建议您在循环播放每个图像之前将样式加载到数组中。我说这是因为我遇到了严重的加载时间问题,因为我必须加载300幅图像,并且对于每个图像,我是分别加载样式而不是之前全部加载样式,这是一个示例,与上面相同:
use Drupal\image\Entity\ImageStyle; // Don't forget this use.
function THEMENAME_preprocess_node__NODETYPE(&$variables){
$node = $variables['node'];
if(isset(node->get('field_images')[0]->entity)){ // Notice how, this time, I check if the FIRST image is set (if it's true, then u'll allow the loop for at least 1 element)
$images_styles = [
'large' => ImageStyle::load('large'),
'thumbnail' => ImageStyle::load('thumbnail')
];
$count = 0;
foreach($node->get('field_images') as $image){
$variables['images'][$count]['large'] = $images_styles['large']->buildUrl($image->getFileUri());
$variables['images'][$count]['thumbnail'] = $images_styles['thumbnail']->buildUrl($image->getFileUri());
$count++;
}
}
}
然后,再次在您的模板(node--NODETYPE.html.twig)中,以这种方式渲染图像:
{% if images %}
<ul>
{% for image in images %}
<li>
<img src="{{ image.large }}" /> // Large image url.
<img src="{{ image.thumbnail }}" /> // Thumbnail image url.
</li>
{% endfor %}
</ul>
{% endif %}
我还没有真正测试过它,所以我想不通,所以它可能包含错误,可以随时警告我,以便我纠正此问题:-)。