【发布时间】:2019-01-08 17:50:12
【问题描述】:
我有一个 Jekyll 站点,我需要在其中显示站点内各种文件的来源。为此,我尝试在我的模板中使用{% include filename %}。然而,事实证明 Liquid 标签include 将只接受_includes 下的路径。最初,我将项目根目录符号链接到_includes 下的路径。这可行,但它使构建变得非常缓慢,因为 Jekyll 需要很长时间才能确定项目中有无限递归的符号链接。
现在,我决定更好的方法是编写一个插件来制作一个full_include 标签,该标签将接受相对于项目基目录的任何路径。代码如下:
#!/usr/bin/env ruby
module MyIncludes
class FullIncludeTag < Liquid::Tag
def initialize(tag_name, filename, other)
super
$stderr.puts "===DEBUG=== Plugin FullIncludeTag initialized. Arguments:\n\ttag_name:\t#{tag_name}\n\tfilename:\t#{filename}\n\tother:\t#{other}"
items = Dir.children(Dir.pwd)
unless items.include?('_config.yml') and items.include('_includes')
raise RuntimeError, "The working directory doesn't appear to be Jekyll's base directory!"
end
@filename = "#{Dir.pwd}/#{filename}"
end
def render(context)
$stderr.puts "===DEBUG=== Plugin FullIncludeTag render beginning.\n\tcontext:\t#{context}\n\tfilename:\t#{@filename}"
# The following two lines produce the exact same output the first time the plugin is called.
$stderr.puts "#{Dir.pwd}/resume/portfolio_entries/raw/dice.py"
$stderr.puts @filename
# File.open "#{Dir.pwd}/resume/portfolio_entries/raw/dice.py" do |f|
# return f.read
# end
File.open @filename do |f|
return f.read.chomp
end
end
end
end
Liquid::Template.register_tag('full_include', MyIncludes::FullIncludeTag)
我的 Ruby 技能非常生疏,因为我已经写了很多年了,但我似乎找不到这里的问题。以下是正在发生的事情:
-
使用呈现的代码,Jekyll 产生以下输出:
===DEBUG=== Plugin FullIncludeTag render beginning. context: #<Liquid::Context:0x018ee008> filename: /home/scott/Main Sync/websites/scottseverance.mss/resume/portfolio_entries/raw/dice.py /home/scott/Main Sync/websites/scottseverance.mss/resume/portfolio_entries/raw/dice.py /home/scott/Main Sync/websites/scottseverance.mss/resume/portfolio_entries/raw/dice.py Liquid Exception: No such file or directory @ rb_sysopen - /home/scott/Main Sync/websites/scottseverance.mss/resume/portfolio_entries/raw/dice.py in resume/portfolio_entries/dice.html jekyll 3.8.4 | Error: No such file or directory @ rb_sysopen - /home/scott/Main Sync/websites/scottseverance.mss/resume/portfolio_entries/raw/dice.py 如果我切换哪个
File.open块被注释掉,那么异常就会消失。当然,由于路径是硬编码的,所以我只能在第一次使用{% full_include %}时得到正确的内容,但这是意料之中的。
请特别注意,代码 cmets 中突出显示的两个 $stderr.puts 调用在任一变体中都会产生相同的输出(至少对于使用硬编码路径调用的液体标签)。因此,我想不出为什么一个电话会起作用而另一个电话会失败。有什么想法吗?
【问题讨论】:
-
唯一能想到的就是
@filename末尾有空格,所以你可能需要@filename.strip。如果您可以显示{% full_include %}的所有调用,那也会很有帮助。 -
@ViktorNonov:事实证明你是对的。
@filename的末尾有一个空格。我在看到你的评论之前就发现了这一点。如果你把它作为一个答案,我会接受它。
标签: ruby jekyll liquid jekyll-extensions