How can a Jekyll page access its filename?

前端 未结 2 1307
耶瑟儿~
耶瑟儿~ 2020-12-15 06:09

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.

相关标签:
2条回答
  • 2020-12-15 06:42

    I'm not sure when this was added, but page.path gives the source file's path relative to the Jekyll root directory.

    0 讨论(0)
  • 2020-12-15 07:00

    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.

    0 讨论(0)
提交回复
热议问题