Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect the current page in a Jekyll tag plugin?

Tags:

jekyll

liquid

I have a Jekyll (Liquid) block plugin and I'd like to detect what the current page is. I see that a context is passed into render, and that I can retrieve the current site object as context.registers[:site]. However, attempts to get the current page as context.registers[:page] fail.

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

Any tips would be greatly appreciated.

Thanks!

like image 243
Seth Ladd Avatar asked Sep 20 '11 00:09

Seth Ladd


3 Answers

Turns out we can also do this like:

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

Which is not obvious but it doesn't require patching the code.

like image 69
Seth Ladd Avatar answered Sep 28 '22 20:09

Seth Ladd


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

so the actual page object can be retrieved with

context.registers[:site].pages.detect { |p| p.path==context['page']['path'] }
like image 21
Partly Cloudy Avatar answered Sep 28 '22 20:09

Partly Cloudy


I don't think there's a good way of doing it with Jekyll as-is. convertible.rb only passes the site object to Liquid, which doesn't contain any page-specific data.

I'd suggest just editing convertible.rb to pass in the data you need, submitting a pull request to the main project to pull in your changes, and using your fork locally to generate your site. Hooray for open source!

The following trivial patch works for me locally against Jekyll 0.11.0, making a page hash available in Liquid as context.registers[:page] (note: it's a pre-converted hash at this point, so you'd access 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 that helps!

like image 27
Mike West Avatar answered Sep 28 '22 19:09

Mike West