![](/img/trans.png)
[英]How to use multiple paragraph custom fields in twig field template in Drupal 8?
[英]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 }}
附注。 您可以执行{{ 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;
}
}
用法
{% set transform = image_style(image.entity.fid.value, ['thumbnail', 'large']) %}
然后您就可以访问源图像和样式
{{ transform.source }}
{{ transform.thumbnail }}
{{ transform.large }}
希望它会帮助你的家伙!
如何在没有 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 %}
可能值得一提的是,首先质疑您的假设很有用。 你真的需要在 Twig 中这样做吗? 如果您可以仅配置视图模式(或视图字段)以使用适当的(响应式)图像样式渲染图像字段,那将简单得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.