如何在 Drupal 8 twig 模板中使用图像样式?

How to use an image style in a Drupal 8 twig template?

我正在尝试使用我在 drupal 8 主题中创建的图像样式来打印图像。

我可以通过执行 {{ content.banner }} 在模板中打印图像,但如何将图像样式应用于该图像?我试着寻找文档,但似乎没有。

目前 drupal 8 没有用于应用图像样式的特殊过滤器。相反,您可以像这样为图像设置新属性:

{% set image = image|merge({'#image_style': 'thumbnail'}) %}

然后简单地输出更新后的图像:

{{ image }}

P.S。您可以执行 {{ dump(image) }} 以查看可以更新哪些属性

我通过创建自己的 Twig 过滤器.

解决了这个问题

您可以通过创建自己的模块来公开此 Filter

随时重复使用它。

代码

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 }}

希望对大家有所帮助!

可能值得一提的是,首先质疑您的假设很有用。你真的需要在 Twig 中这样做吗?如果您可以配置视图模式(或视图字段)以使用适当的(响应式)图像样式渲染图像字段,那会简单得多。

如何在没有 contrib 模块的情况下执行此操作:将其设为您自己的渲染数组。

{% 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 %}