古腾堡自定义块与响应图像

时间:2018-08-16 22:44:34

标签: wordpress srcset wordpress-gutenberg gutenberg-blocks

我按照本教程介绍了如何构建自定义WordPress古登堡块:https://neliosoftware.com/blog/how-to-create-your-first-block-for-gutenberg/

这第一个块很好,但是我想在这个块中使用自定义图像大小。该图像大小还应该具有响应性,这意味着应该在前端srcset属性上添加其他图像大小。

我在互联网上搜索了很长时间,但没有找到任何东西。对于标准的图像块或画廊块,使用了来自wordpress的调整大小的图像,但是对我来说,整个代码太复杂了,无法遵循,因为我还不习惯使用Gutenberg的编码方式。

是否存在有关如何进行归档的指南或代码示例?

最佳 卢卡斯

1 个答案:

答案 0 :(得分:2)

我在this gutenberg github issue的帮助下找到了解决方案。简单的答案是,wordpress(php)使用wp_make_content_images_responsive函数自动转换所有具有类名wp-image-<id>的图像。

也就是说,您要做的就是在save函数中将上述类名称添加到图像中。

应用到您提到的示例中,就像下面这样:

save: function( props ) {
  var attributes = props.attributes;
  var alignment = props.attributes.alignment;
  var imageClass = 'wp-image-' + props.attributes.mediaId;

  return (
    el( 'div', { className: props.className },
      attributes.mediaURL &&
      el( 'div', { className: 'nelio-testimonial-image', style: { backgroundImage: 'url('+attributes.mediaURL+')' } },
        el( 'img', { src: attributes.mediaURL, class: imageClass } ),
      ),
      el( 'div', { className: 'nelio-testimonial-content', style: { textAlign: attributes.alignment } },
        attributes.testimonial && el( 'p', {}, attributes.testimonial ),
        el( 'p', { className: 'nelio-testimonial-name' }, attributes.name ),
        attributes.position && el( 'p', { className: 'nelio-testimonial-position' }, attributes.position )
      )
    )
  );
},