Anomareh/mynt — pull request #66 by shamansir (2014-08-30 12:46:08+00:00)
Title: Support Table of Contents (aka T.O.C.) generation for Posts

This generation is completely optional and only works if TOCs are enabled in blog `config.yml`, like this:

```
hoep:
render_flags:
toc: true
```

In that case, all posts get an additional attribute, `item.toc`, which is an object that represents a TOC tree, starting from a root (empty) leaf.

#### Leaf Attributes

Every leaf has these attributes:

* `leaf.hlevel` — the value of `n` from `` tag which was used to generate this leaf;
* `leaf.level` — how deep is level in a tree, `0` is root;
* `leaf.parent` — parent leaf, `None` for root node;
* `leaf.children` — leaf children, in array;
* `leaf.text` — `text`, text from inside of a header tag, `None` for root;
* `leaf.identifier` — anchor ID, from `text`, `None` for root;

If there were no headings found in a post, root leaf has no children (array is empty).

#### Example Macro

Example macro to generate an `UL`-tree from this object (`_templates/macros.html`):

```
{% macro toc(leaf) %}
{% if leaf %}
{% if leaf.parent %}
{# the root leaf has no parent #}

{{ leaf.text }}
{% if leaf.children %}

{% for subleaf in leaf.children %}
{{ toc(subleaf) }}
{% endfor %}

{% endif %}

{% else %}
{# the root leaf should just fall inside #}
{% for subleaf in leaf.children %}
{{ toc(subleaf) }}
{% endfor %}
{% endif %}
{% endif %}
{%- endmacro %}
```

#### Example Macro Usage

`_templates/layout.html` or `_templates/post.html`:

```
{% from 'macros.html' import toc as build_toc %}
```

`_templates/post.html`:

```
{% if post.toc %}
{% block toc %}

Contents:

{{ build_toc(post.toc) }}

{% endblock %}
{% endif %}
```

Cons:
I haven't found a way to return TOC object properly from a parser, so now it returns a tuple from `.render` method in case if TOCs are enabled, very possibly it's not a honest way to do it :).