Loading...

August 5, 2014

Awesome Asciidoctor: Using Conditional Directives

In Asciidoc markup we can include or exclude text based on the existence of document attributes or based on the value of a document attribute. Therefore we use the macros ifdef, ifndef and ifeval. If we want to include some content if the document attribute sample is set we can use the following syntax:

ifdef::sample[Content is shown when sample attribute is set]

ifdef::sample[]
Content is shown when sample attribute is set
endif::sample[]

If we want to include some content if the attribute is not set we use ifndef:

ifndef::sample[Content is shown when sample attribute is NOT set]

ifndef::sample[]
Content is shown when sample attribute is NOT set
endif::sample[]

We can even use multiple attributes for these macros. If the attribute names are , separated only one of the attributes need to be set to include the content. If we use the + separator all attributes must be set to include the content.

In the following sample Asciidoc markup we see several usages of the ifdef and ifndef macros:

|===
| Attributes

|
ifdef::intermediate[:intermediate:]
ifndef::intermediate[:intermediate!:]

|
ifdef::advanced[:advanced:]
ifndef::advanced[:advanced!:]

|===


ifdef::advanced[]
This is only visible if we 
set the advanced attribute.
endif::advanced[]

ifdef::intermediate,advanced[]
Here is some content for the
intermediate or advanced readers,
which is visible if the attributes
intermediate or advanced are set.
endif::intermediate,advanced[]

ifdef::intermediate+advanced[]
Here is some content for the
intermediate and advanced readers,
which is visible if the attributes
intermediate AND advanced are set.
endif::intermediate+advanced[]

If we generate HTML output and set and unset the intermediate and advanced document attributes we see that content is included or not:




Finally with Asciidoctor we can use the ifeval macro to evaluate the value of attributes. If the expression evaluates to true the content is included otherwise it is skipped. The following sample evaluate the version document attribute and shows different content based on the value:

|===
| Attributes

|
:version: {version}

|===


ifeval::[{version} >= 1]
We are live!
endif::[]


ifeval::[{version} < 1]
Still developing...
endif::[]

Let's generate HTML with different values for the version attribute:

Written with Asciidoctor 0.1.4.