summaryrefslogtreecommitdiff
path: root/docs/modules/extensions/pages/preprocessor.adoc
blob: d1cc95f19c469637cd6afbe71ec1424adb82d1c0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
= Preprocessor Extension Example
:navtitle: Preprocessor

Purpose::
Skim off front matter from the top of the document that gets used by site generators like Jekyll and Awestruct.

== sample-with-front-matter.adoc

[source,asciidoc]
----
tags: [announcement, website]
---
= Document Title

content

[subs=+attributes]
.Captured front matter
....
---
{front-matter}
---
....
----

== FrontMatterPreprocessor

[source,ruby]
----
require 'asciidoctor'
require 'asciidoctor/extensions'

class FrontMatterPreprocessor < Asciidoctor::Extensions::Preprocessor
  def process document, reader
    lines = reader.lines # get raw lines
    return reader if lines.empty?
    front_matter = []
    if lines.first.chomp == '---'
      original_lines = lines.dup
      lines.shift
      while !lines.empty? && lines.first.chomp != '---'
        front_matter << lines.shift
      end

      if (first = lines.first).nil? || first.chomp != '---'
        lines = original_lines
      else
        lines.shift
        document.attributes['front-matter'] = front_matter.join.chomp
        # advance the reader by the number of lines taken
        (front_matter.length + 2).times { reader.advance }
      end
    end
    reader
  end
end
----

== Usage

[source,ruby]
----
Asciidoctor::Extensions.register do
  preprocessor FrontMatterPreprocessor
end

Asciidoctor.convert_file 'sample-with-front-matter.adoc', safe: :safe
----