How to create a liquid tag extension which return filename in Jekyll
Asked Answered
H

3

9

It's pretty basic stuff, I guess but I couldn't figure out how to do it.

What I want to do is very simple.

By using Jekyll plugin system, I want to extend Liquid tag to return filename of post.

{{% page.filename %}}

will parse to something like

jekyll-plugin.markdown
Hama answered 23/7, 2011 at 1:20 Comment(0)
S
3

Well, it's not exactly the method you're looking for, but you could just include the filename in the yaml headers for the file. It's probably a bad choice for files that you'll move around and tweak, but since there don't appear to be a wealth of answers pouring forth, maybe it's good enough.

Sottish answered 25/7, 2011 at 14:37 Comment(0)
H
1

I think I got it. Here I´m checking if a file has a line that contains "Filename:". If not, it places it on the second line, with the variable of the filename.

#!/bin/bash
for file in $(ls *.md)
do
if grep -Fq "filename: " $file
then
   # code if not found
   echo "File: $file already processed"
else
    # code if found
    echo "Adding the line on file: $file"
    awk -v n=2 -v s="filename: $file" 'NR == n {print s} {print}' $file > tmp.txt
    mv tmp.txt $file
fi

done

Hydrastinine answered 6/7, 2012 at 7:39 Comment(0)
D
1

Here you go, stick the following in _plugins/filename.rb and the file's basename will be accessible in page.filename:

require 'pathname'

module Jekyll
  class Filename
    def self.hook_proc
      proc { |page|
        page.data['filename'] = Filename.new(Pathname.new(page.path).basename)
      }
    end

    def initialize(filename)
      raise "empty filename" if filename.empty?
      @filename = filename
    end

    def to_liquid
      @filename
    end
  end

  Hooks.register :pages, :post_init, &Filename.hook_proc
  Hooks.register :documents, :post_init, &Filename.hook_proc
end

If you want the whole path, just s/Pathname.new(page.path).basename/page.path/ (and delete require 'pathname')

Dasteel answered 9/11, 2022 at 21:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.