Showing posts and tags with Franklin.jl

Sebastian Pfitzner
franklin html julia

If you're using Franklin.jl to generate a blog-style page, you'll likely want to show your most recent posts somewhere. The following code, heavily inspired by https://mcognetta.github.io/posts/recent-posts-list/, returns a list of all posts in the /posts subdirectory

function sorted_posts()
  posts_dir = joinpath(@__DIR__, "posts")
  posts = []

  for _dir in readdir(posts_dir)
    dir = joinpath(posts_dir, _dir)
    indexfile = joinpath(dir, "index.md")
    if isdir(dir) && isfile(indexfile)
      date =  pagevar(relpath(indexfile, @__DIR__), :date)
      urlpath = string("/", relpath(dir, @__DIR__))
      push!(
        posts, (
          date = Date(date, "yyyy/mm/dd"),
          humandate = date,
          page = urlpath,
          title = pagevar(relpath(indexfile, @__DIR__), :title)
        )
      )
    end
  end
  sort!(posts; by = post -> post.date, rev = true)

  return posts
end

Note that you need to set a local variable date for each post like this:

@def date = "2022/11/27"

With that, it's trivial to show a list of recent posts

function hfun_recents(N = 5)
  posts = sorted_posts()

  return Franklin.md2html(join((
    "* [$(post.humandate): $(post.title)]($(post.page))" 
    for post in posts[1:min(end, N)]), "\n"))
end

or all posts, partitioned by year:

function hfun_all_posts_partitioned()
  posts = sorted_posts()
  io = IOBuffer()
  last_year = 0

  for post in posts
    if last_year < year(post.date)
      last_year = year(post.date)
      println(io, "### $(year(post.date))")
    end

    println(io, "* [$(post.title)]($(post.page))")
  end

  return Franklin.md2html(String(take!(io)))
end
© JuliaHub
Website built with Franklin.jl and the Julia programming language