Get Jekyll Configuration Inside Plugin

后端 未结 3 888
陌清茗
陌清茗 2021-02-07 03:58

I\'d like to make changes to the Jekyll Only First Paragraph plugin to make the generation of a \'read more \' link a configurable option.

To do this I\'d need to be abl

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-07 04:48

    Overview

    You can access Jekyll config options in plugins with:

    Jekyll.configuration({})['KEY_NAME']
    

    If the config key contains nested levels, the format is:

    Jekyll.configuration({})['KEY_LEVEL_1']['KEY_LEVEL_2']
    

    Example

    If a _config.yml contains:

    testvar: new value
    
    custom_root:
        second_level: sub level data
    

    A basic example that simply outputs those values would look like:

    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 = "

    " ### Confirm you got the config values output << "
    " output << "c_value: " + @c_value + "
    " output << "c_value_nested: " + @c_value_nested + "
    " output << "
    " ### output << Nokogiri::HTML(post["content"]).at_css("p").inner_html output << %{

    Read more} output end end end Liquid::Template.register_filter(Jekyll::AssetFilter)

    Of course, you would want to put checks in that verify that the config key/values are defined before trying to use them. That's left as an exercise for the reader.


    Another Possible Option

    The "Liquid filters" section of the Jekyll Plugins Wiki Page contains the following:

    In Jekyll you can access the site object through registers. As an example, you can access the global configuration (_config.yml) like this: @context.registers[:site].config['cdn'].

    I haven't spent the time to get that to work, but it might be worth checking out as well.

提交回复
热议问题