Pandoc: Lua-Filter for replacing {{helloworld}} with <div>abc</div>

Viewed 1314

In the manual I found this example of an pandoc lua-filter:

return {
  {
    Str = function (elem)
      if elem.text == "{{helloworld}}" then
        return pandoc.Emph {pandoc.Str "Hello, World"}
      else
        return elem
      end
    end,
  }
}

I want to replace {{helloworld}} with <div>abc</div>. My try:

return {
  {
    Str = function (elem)
      if elem.text == "{{helloworld}}" then
        return pandoc.RawInline('html','<div>abc</div>')
      else
        return elem
      end
    end,
  }
}

...but this give me the following output:

<p></p>
<div>abc</div>
<p></p>

How can I get rid of the empty p-tags?

Additional information

I convert from markdown to html and my markdown file looks like this:

enter image description here

1 Answers

The manual says:

The function’s output must result in an element of the same type as the input. This means a filter function acting on an inline element must return either nil, an inline, or a list of inlines, and a function filtering a block element must return one of nil, a block, or a list of block elements. Pandoc will throw an error if this condition is violated.

You want your output to be rendered as a block (<div>abc</div>) but your input (Str) is inline. That's why it doesn't work. Change Str (Inline) to Para (Block), elem.text to element.content[1].text and RawInline to RawBlock and it will work:

return {
  {
    Para = function (elem)
      if elem.content[1].text == "{{helloworld}}" then
        return pandoc.RawBlock('html','<div>abc</div>')
      else
        return elem
      end
    end,
  }
}
Related