Tyl*_*all 10 drupal twig drupal-8
我正在尝试使用我在drupal 8主题中创建的图像样式打印图像.
我可以通过{{content.banner}}在模板中打印图像,但如何将图像样式应用于该图像?我试着找文件,但似乎没有任何东西.
pav*_*ich 12
目前drupal 8没有用于应用图像样式的特殊过滤器.相反,您可以为此图像设置新属性,如下所示:
{% set image = image|merge({'#image_style': 'thumbnail'}) %}
Run Code Online (Sandbox Code Playgroud)
然后只需输出更新的图像:
{{ image }}
Run Code Online (Sandbox Code Playgroud)
PS.您可以{{ dump(image) }}
查看可以更新的属性
我通过创建我自己的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;
}
}
Run Code Online (Sandbox Code Playgroud)
用法
{% set transform = image_style(image.entity.fid.value, ['thumbnail', 'large']) %}
Run Code Online (Sandbox Code Playgroud)
然后您就可以访问源图像和样式
{{ transform.source }}
{{ transform.thumbnail }}
{{ transform.large }}
Run Code Online (Sandbox Code Playgroud)
希望它会帮助你的家伙!