带有响应式图像的古腾堡自定义块

Luk*_*uke 4 wordpress srcset wordpress-gutenberg gutenberg-blocks

我遵循了有关如何构建自定义 WordPress Gutenberg 块的教程:https : //neliosoftware.com/blog/how-to-create-your-first-block-for-gutenberg/

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

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

是否有关于如何存档的现有指南或代码示例?

最好的卢卡斯

nik*_*las 10

我在这个古腾堡 github 问题的帮助下找到了一个解决方案。简单的答案是,wordpress (php)wp-image-<id>使用wp_make_content_images_responsive函数转换所有类名为自动响应的图像

也就是说,您需要做的就是在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 )
      )
    )
  );
},
Run Code Online (Sandbox Code Playgroud)