How to define current page in Jekyll tag plugin?

I have a Jekyll (Liquid) block plugin and I would like to know what the current page is. I see that the context is being passed to render, and that I can get the current site object as context.registers [: site]. However, attempts to get the current page as context.registers [: page] failed.

The problem I'm trying to solve is to create a simple block plugin to determine if the current page is the page indicated in the tag and highlight it.

Any advice is appreciated.

Thanks!

+6
source share
3 answers

It turns out we can also do this as follows:

def render(context) page_url = context.environments.first["page"]["url"] 

This is not obvious, but does not require code correction.

+15
source

context['page'] seems to return a hash with most of the properties of the current page, including url and path

therefore, the actual page object can be obtained using

 context.registers[:site].pages.detect { |p| p.path==context['page']['path'] } 
+2
source

I don't think there is a good way to do this with Jekyll as it is. convertible.rb passes the site object only to Liquid, which does not contain any data related to the page.

I would suggest just editing convertible.rb to transfer the data you need by sending a transfer request to the main project to pull your changes, and using your fork locally to create your site. Hooray for open source!

The following trivial patch works for me locally against Jekyll 0.11.0, making the hash of the page available in Liquid as context.registers[:page] (note: this is a pre-converted hash at this point, so you will get access to context.registers[:page]['url'] , not context.registers[:page].url ):

 diff --git a/lib/jekyll/convertible.rb b/lib/jekyll/convertible.rb index d33abc5..a674ef5 100644 --- a/lib/jekyll/convertible.rb +++ b/lib/jekyll/convertible.rb @@ -69,7 +69,7 @@ module Jekyll # # Returns nothing. def do_layout(payload, layouts) - info = { :filters => [Jekyll::Filters], :registers => { :site => self.site } } + info = { :filters => [Jekyll::Filters], :registers => { :site => self.site, :page => payload['page'] } } # render and transform content (this becomes the final content of the object) payload["pygments_prefix"] = converter.pygments_prefix 

Hope this helps!

+1
source

Source: https://habr.com/ru/post/897648/


All Articles