我正在尝试使用我在Drupal 8主题中创建的图像样式来打印一张图片。
我可以通过 {{ content.banner }} 在模板中打印一个图片,但是如何将图像样式应用于该图片?我尝试寻找文档,但似乎没有任何文档可用。
目前Drupal 8没有专门的过滤器来应用图像样式。相反,您可以为图像设置新属性,如下所示:
{% set image = image|merge({'#image_style': 'thumbnail'}) %}
然后简单地输出您更新后的图像:
{{ image }}
提示:您可以执行{{ dump(image) }}
以查看可以更新的属性
namespace Drupal\twig_extender\TwigExtension;
use Drupal\node\Entity\Node;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
class Images extends \Twig_Extension {
/**
* Generates a list of all Twig functions that this extension defines.
*/
public function getFunctions(){
return array(
new \Twig_SimpleFunction('image_style', array($this, 'imageStyle'), array('is_safe' => array('html'))),
);
}
/**
* Gets a unique identifier for this Twig extension.
*/
public function getName() {
return 'twig_extender.twig.images';
}
/**
* Generate images styles for given image
*/
public static function imageStyle($file_id, $styles) {
$file = File::load($file_id);
$transform = array();
if (isset($file->uri->value)) {
$transform['source'] = $file->url();
foreach ($styles as $style) {
$transform[$style] = ImageStyle::load($style)->buildUrl($file->uri->value);
}
}
return $transform;
}
}
用法
{% set transform = image_style(image.entity.fid.value, ['thumbnail', 'large']) %}
然后您就可以访问源图像和样式
{{ transform.source }}
{{ transform.thumbnail }}
{{ transform.large }}
/modules/custom_module/src/TwigExtension/Images.php
中,但仍然出现错误Twig_Error_Syntax: Unknown "image_style" function. in Twig_ExpressionParser->..
。 - ARUN{% for item in content.field_images['#items'] %}
{% set image = {
'#theme': 'image_style',
'#style_name': 'medium',
'#uri': item.entity.uri.value,
'#alt': item.alt,
'#width': item.width,
'#height': item.height
} %}
{{ image }}
{% endfor %}
值得一提的是,首先质疑自己的假设是很有用的。你真的需要在Twig中完成这个任务吗?如果你可以通过配置视图模式(或Views字段)以适当的(响应式)图像样式呈现图像字段,那将会更简单。