LazyLoad带有变量的Jekyll图像

LazyLoad Jekyll images with variables

本文关键字:Jekyll 图像 变量 LazyLoad      更新时间:2024-06-06

我正试图延迟加载具有{{page.path}}变量的jekyll图像。不幸的是,当我使用路径并使用硬链接的图像时,可用的jekyll插件会崩溃。我在布局中使用变量在多个页面上显示图像,所以我绝对不想开始使用硬编码的绝对路径。

插件基本上可以处理lazylod类的添加,找到w/h并渲染具有相关类和维度的图像。下面是来自https://gist.github.com/ttscoff/9035690我需要修改什么才能允许将jekyll变量作为路径?或者有没有一种更好的方法来实现我没有想到的懒惰?作为参考,我的img路径通常是:

![My helpful screenshot](/images/{{ page.id }}/1.jpg)

图像标签插件

module Jekyll
class ImageTag < Liquid::Tag
@img = {}
def initialize(tag_name, markup, tokens)
  # <img class="lazy" src="img/grey.gif" data-original="img/example.jpg" width="640" height="480">
  if markup =~ /(?:('S+) )?((?:https?:'/'/|'/|'S+'/)'S+)(?:'s+('d+))?(?:'s+('d+))?'s+(.*)?/i
    unless $2.nil?
      imgclass = $1 || nil
      image = $2
      width = $3 || nil
      height = $4 || nil
      title = $5 || nil
      @img = {}
      @img["class"] = imgclass ? "lazy #{imgclass}" : "lazy"
      begin
        if image =~ /^(http:'/'/brettterpstra.com|'/)/
          image.sub!(/^(http:'/'/brettterpstra.com)?/,"")
          @img["data-original"] = image
          filename = File.expand_path(File.join(%x{git rev-parse --show-toplevel}.strip,"source"+image))
          @img["width"] = width || filename ? %x{sips -g pixelWidth "#{filename}"|awk '{print $2}'}.strip : nil
          @img["height"] = height || filename ? %x{sips -g pixelHeight "#{filename}"|awk '{print $2}'}.strip : nil
        else
          @img["data-original"] = image
          @img["width"] = width if width
          @img["height"] = height if height
        end
      rescue
        @img["data-original"] = image
        @img["width"] = width if width
        @img["height"] = height if height
      end
      @img["src"] = "/images/grey.gif"
      if title && title !~ /^['s"]*$/
        if /(?:"|')(?<xtitle>[^"']+)?(?:"|')'s+(?:"|')(?<alt>[^"']+)?(?:"|')/ =~ title
          @img['title']  = xtitle
          @img['alt']    = alt
        else
          @img['alt']    = title.gsub(/(^["'s]*|["'s]*$)/, '')
        end
      end
    end
  end
  super
end
def render(context)
  unless @img.empty?
    if context.registers[:site].config["production"]
      @img["src"] = context.registers[:site].config["cdn_url"] + @img["src"]
      if @img["data-original"] =~ /^(http:'/'/brettterpstra.com|'/)/
        @img["data-original"] = context.registers[:site].config["cdn_url"] + @img["data-original"]
      end
    end
    %Q{<img #{@img.collect {|k,v| "#{k}='"#{v}'"" if v}.join(" ")}>}
  else
    "Error processing input, expected syntax: {% img [class name(s)] [http[s]:/]/path/to/image [width [height]] [title text | '"title text'" ['"alt text'"]] %}"
   end
 end
 end
end
Liquid::Template.register_tag('img', Jekyll::ImageTag)

您可以查看Alexander Farkas lazyzes