ruby - Jekyll:在不使用外部插件的情况下获取图像的宽度/高度

标签 ruby jekyll github-pages

我要自动添加heightwidth属性到我所有的图像。它是通过 this nice plugin 完美完成的,但我在不支持外部插件的 GitHub 页面上托管我的网站。

问题:如何在不使用插件的情况下预填充图像的高度/宽度属性?

为什么我需要这个?

My site即使没有 height 也能正常工作和 width但我想指定它们,因为从 SEO 的角度来看它很重要(您可以找到有关其重要性的一些详细信息 here)。

最佳答案

使用 fastimage gem 编写一个内部过滤器来执行此操作相当简单。您可以在 _plugins 中定义您的过滤器项目目录(在 Jekyll documentation 中概述)
作为一个非常粗略的例子,你可以做这样的事情:

require 'fastimage'

module ImageSizeFilter
  def image_size(source, dimension = nil)
    # Get the image dimensions, throw an error on failure
    # NOTE: You may want to sanitize the input string provided here
    # see: https://github.com/sdsykes/fastimage#security
    size = FastImage.size(source, raise_on_failure: true)

    # Return the requested dimension, or both dimensions if nothing was specified
    return size[0] if dimension == 'w'
    return size[1] if dimension == 'h'
    return size unless dimension

    # Fail if the requested dimension is invalid
    raise 'Invalid image size dimension requested: ' + dimension
  end
end

Liquid::Template.register_filter(ImageSizeFilter)
将像这样使用:
<img src={{source}}
     width="{{source | image_size: 'w'}}"
     height="{{source | image_size: 'h'}}"/>
当然,这仍然不能直接与 GitHub 页面一起使用,因为不支持自定义插件。要一般使用自定义插件,一种解决方案是 build the site locally and include it in the repository .

关于ruby - Jekyll:在不使用外部插件的情况下获取图像的宽度/高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53309750/

相关文章:

ruby - 在 Mac Big Sur M1 上安装 Ruby 2.2.9 时出现问题

ruby - 如何通过包含模块来包装 Ruby 方法的调用?

jekyll - 使用 Github Pages 托管的 Jekyll 站点中是否需要 gemfile.lock 文件?

ruby - 在 ubuntu 上安装 ruby​​ 要求

git - 如何使用 index.html 作为子目录的符号链接(symbolic link)在 gh-pages 中部署

subdomain - 一个 CNAME 文件用于 2 个不同的域。 gh-pages X namecheap

github-pages - 如何在 Github Pages 上修改已部署的 create-react-app?

Ruby 命名约定/双下划线/有用的东西

ruby-on-rails - 建模团队

ruby - socket @ rb_sysopen 不支持操作