Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a Jekyll page access its filename?

Tags:

My goal is to create links from any published jekyll page back to its location on Github.

And so, I'd need access to a page's pathname when constructing this url. However, I don't see anything in the api for templates that provides this info. I looked at the source for page, but none of the file/path attributes had values, when accessed via the template.

like image 214
Dogweather Avatar asked Nov 06 '12 02:11

Dogweather


1 Answers

Update: nowadays you can use {{page.path}}.


It seems like you can construct your link just fine using the liquid code: {{ page.url }}

For instance, if you want this page: http://railsdocs.org/pages/get-involved.html to link to this page: https://github.com/dogweather/railsdocs.org/blob/gh-pages/pages/get-involved.md

Seems like you could add something like:

[source](https://github.com/dogweather/railsdocs.org/blob/gh-pages/{{page.url | replace:'.html','.md'}}) 

to the markdown and get the link you want.

A more general solution:

Alternatively, we could write a generator that allows a page to access its file name directly. Add this to a .rb file in your _plugins directory:

module Jekyll    class PagePathGenerator < Generator     safe true     ## See post.dir and post.base for directory information.      def generate(site)       site.posts.each do |post|         post.data['path'] = post.name       end      end   end  end 

and then we can reliably get the post's filename as {{ page.path }}. This solution is more robust than converting from the URL, since page names can have characters that get 'sanitized' out when converting them to URLs. (Posts would also need their date information, etc added back in). Instead, this plugin gives us direct access to a post's name.

A similar strategy could allow us to get the path to the post if that data is also needed.

like image 150
cboettig Avatar answered Dec 09 '22 04:12

cboettig