获取Jekyll配置内插件

Jon*_*ram 16 ruby liquid jekyll

我想对Jekyll Only First Paragraph插件进行更改,以便将"read more"链接生成为可配置选项.

要做到这一点,我需要能够访问插件内的Jekyll站点配置AssetFilter.有了可用的配置,我可以进行更改.我不知道如何使插件可以使用站点配置.

下面的代码演示了我想要的地方site.config:

require 'nokogiri'

module Jekyll
  module AssetFilter
    def only_first_p(post)
      # site.config needs to be available here to modify the output based on the configuration

      output = "<p>"
      output << Nokogiri::HTML(post["content"]).at_css("p").inner_html
      output << %{</p><a class="readmore" href="#{post["url"]}">Read more</a>}

      output
    end
  end
end

Liquid::Template.register_filter(Jekyll::AssetFilter)
Run Code Online (Sandbox Code Playgroud)


这可以实现吗?

Ala*_*ith 20

概观

您可以使用以下命令访问插件中的Jekyll配置选项:

Jekyll.configuration({})['KEY_NAME']
Run Code Online (Sandbox Code Playgroud)

如果配置密钥包含嵌套级别,则格式为:

Jekyll.configuration({})['KEY_LEVEL_1']['KEY_LEVEL_2']
Run Code Online (Sandbox Code Playgroud)

如果_config.yml包含:

testvar: new value

custom_root:
    second_level: sub level data
Run Code Online (Sandbox Code Playgroud)

简单输出这些值的基本示例如下所示:

require 'nokogiri'

module Jekyll
  module AssetFilter
    def only_first_p(post)

      @c_value = Jekyll.configuration({})['testvar']
      @c_value_nested = Jekyll.configuration({})['custom_root']['second_level']

      output = "<p>"

      ### Confirm you got the config values
      output << "<br />"
      output << "c_value: " + @c_value + "<br />"
      output << "c_value_nested: " + @c_value_nested + "<br />"
      output << "<br />"
      ###

      output << Nokogiri::HTML(post["content"]).at_css("p").inner_html
      output << %{</p><a class="readmore" href="#{post["url"]}">Read more</a>}

      output
    end
  end
end

Liquid::Template.register_filter(Jekyll::AssetFilter)
Run Code Online (Sandbox Code Playgroud)

当然,您可能希望在尝试使用它们之前验证是否已定义配置键/值.这是留给读者的练习.


另一个可能的选择

Jekyll插件Wiki页面的"Liquid filters"部分包含以下内容:

在Jekyll中,您可以通过寄存器访问站点对象.例如,您可以像这样访问全局配置(_config.yml):@ context.registers [:site] .config ['cdn'].

我没有花时间让它工作,但也可能值得一试.

  • `Jekyll.configuration({})`解决方案的一个问题可能是每次调用都会执行整个"从YAML文件加载配置"进程.这为Jekyll 1.0-rc1生成了大量的日志输出,所以我采用了"上下文"解决方案. (4认同)
  • `context.registers [:site] .config ['cdn']`对我很有用! (4认同)

bas*_*sex 14

Jekyll.configuration({})['KEY_NAME']将断开--config命令行选项,因为它将始终从_config.yml文件加载配置.另一个不好的副作用是它会再次读取_config.yml文件.

context.registers[:site].config['KEY_NAME'] 是正确的答案,因为它将从已经由Jekyll加载的配置中获取密钥.

  • 什么是“上下文”? (2认同)