12

drupal 8 テーマで作成した画像スタイルを使用して画像を印刷しようとしています。

{{ content.banner }} を実行してテンプレートの画像を印刷できますが、その画像に画像スタイルを適用するにはどうすればよいですか? ドキュメントを探してみましたが、そこにはないようです。

4

4 に答える 4

13

現在、drupal 8 には、画像スタイルを適用するための特別なフィルターはありません。代わりに、次のように画像に新しい属性を設定できます。

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

次に、更新した画像を出力するだけです。

{{ image }}

PS。{{ dump(image) }}更新できる属性を確認するために行うことができます

于 2015-11-12T10:56:17.510 に答える
5

これを解決するには、独自のTwig Filterを作成します。

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

それがあなたの助けになることを願っています!

于 2016-07-28T08:23:22.600 に答える