Sr. Schneider
Sr. Schneider

Reputation: 757

Pandoc Lua Filter: How to access the title variable?

My document looks like this

---
title: 'Test'
---

lorem ipsum

I want to access the title variable to print it like this:

function Image (elem)
elem.attributes.caption = 'Image of chapter ' .. title
return elem

The caption of all images should be: 'Image of chapter Test'.

Upvotes: 3

Views: 428

Answers (2)

Thomas Weller
Thomas Weller

Reputation: 59303

You can access variables like properties at the meta object, or you can access them like elements of a dictionary. The latter is especially important if you have variables in your YAML block that contain hyphens, like e.g. payment-due.

function Meta(meta)
    print(meta.title)
    print(meta["payment-due"])

The type of such a variable is table. You can check that using type():

    print(type(meta.title))
    print(type(meta["payment-due"]))

To convert it into a string, you can use pandoc.utils.stringify(). Just make sure that the value is actually set and is not nil:

    if meta.title ~= nil then
      local title = pandoc.utils.stringify(meta.title)
      print(title)
    end

Hint: don't use tostring(). Your variable will then look like [Str "Test"].

Upvotes: 0

mb21
mb21

Reputation: 39243

Something like this should work (untested), inspired by the docs:

title = nil

function Meta(m)
  title = m.title
  return m
end

function Image (elem)
  elem.attributes.caption = 'Image of chapter ' .. title
  return elem
end

Upvotes: 3

Related Questions