Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,28 @@ With a plain ``{{ mysubdoc }}`` the paragraphs end up inside the text of the par
and, if the paragraph also has other content such as a bookmark or formatted text, the generated document may be corrupted and refused by Word.
The same goes for subdocs inserted in a loop: put the tag in its own ``{%p for ... %}`` block and use ``{{p item }}`` inside it.

.. rubric:: Multilevel numbered lists

In Word, create one multilevel list in the template. For example, use decimal
numbers at level 1, lower-case letters at level 2, and lower-case Roman numerals
at level 3. Set the second level to restart after level 1 and the third level to
restart after level 2. Apply that list directly to the paragraph whose only
text is the tag ``{{p items }}``.

Read the numbered paragraph's list ID (``numId``) and use it for every generated
paragraph. Set each paragraph's zero-based list level (``ilvl``) in the subdoc.
With separate numbering IDs for the levels, Word keeps separate counters and
the child numbering can continue under a new parent.

``pip install "docform[subdoc]"`` installs the dependencies for this example.
Use the :download:`example template <../examples/multilevel_list/template.docx>`
and run the :download:`render script <../examples/multilevel_list/render.py>`.
Open the output in Word to see the numbering restart as
``1., a., b., i., ii., 2., a., i.``.

.. literalinclude:: ../examples/multilevel_list/render.py
:language: python

.. _Escaping:

Escaping
Expand Down
2 changes: 2 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ Each folder has a template, the data it's rendered with, and a `render.py` scrip
| Example | Shows |
|---|---|
| [invoice](invoice) | Variables, a table row loop with `{%tr %}`, paragraph conditions with `{%p %}`, and formatting carried over from tags |
| [multilevel list](multilevel_list) | A numbered subdoc whose child levels restart under each new parent |

Run one from the repo root:

```bash
python examples/invoice/render.py
python examples/multilevel_list/render.py
```
40 changes: 40 additions & 0 deletions examples/multilevel_list/render.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""Render a numbered list with Word-managed restarts."""

from pathlib import Path

from docform import DocxTemplate

ITEMS = (
(0, "Prepare the report"),
(1, "Collect the data"),
(1, "Review the figures"),
(2, "Check the axis labels"),
(2, "Check the units"),
(0, "Publish the report"),
(1, "Prepare the release"),
(2, "Check the metadata"),
)


def render(template_path, output_path, items):
tpl = DocxTemplate(template_path)
# Read the list instance from the numbered placeholder in the template.
placeholder = next(p for p in tpl.get_docx().paragraphs if p.text == "{{p items }}")
num_id = placeholder._p.pPr.numPr.numId.val

subdoc = tpl.new_subdoc()
for level, text in items:
paragraph = subdoc.add_paragraph(text)
numbering = paragraph._p.get_or_add_pPr().get_or_add_numPr()
numbering.get_or_add_ilvl().val = level
numbering.get_or_add_numId().val = num_id

tpl.render({"items": subdoc})
tpl.save(output_path)


if __name__ == "__main__":
here = Path(__file__).resolve().parent
output = here / "multilevel_list.docx"
render(here / "template.docx", output, ITEMS)
print("Wrote", output)
Binary file added examples/multilevel_list/template.docx
Binary file not shown.
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ ignore_missing_imports = true
[tool.pdm]
version = {source="file", path="docform/__init__.py"}

[tool.pdm.build]
source-includes = ["tests/", "examples/multilevel_list/"]

[build-system]
requires = ["pdm-backend"]
build-backend = "pdm.backend"
29 changes: 29 additions & 0 deletions tests/unit/test_multilevel_list_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import runpy
from pathlib import Path

from docx import Document


def test_multilevel_list_example_keeps_one_list_with_explicit_levels(tmp_path):
example = Path(__file__).resolve().parents[2] / "examples" / "multilevel_list"
code = runpy.run_path(str(example / "render.py"))
template = example / "template.docx"
output = tmp_path / "multilevel_list.docx"

code["render"](template, output, code["ITEMS"])

doc = Document(output)
assert [paragraph.text for paragraph in doc.paragraphs] == [
text for _, text in code["ITEMS"]
]
num_ids = {paragraph._p.pPr.numPr.numId.val for paragraph in doc.paragraphs}
template_num_id = Document(template).paragraphs[0]._p.pPr.numPr.numId.val
assert num_ids == {template_num_id}
numbering = doc.part.numbering_part.element
abstract_id = numbering.num_having_numId(template_num_id).abstractNumId.val
level_path = f'./w:abstractNum[@w:abstractNumId="{abstract_id}"]/w:lvl'
assert len(numbering.xpath(level_path)) == 3
assert not numbering.xpath(level_path + "/w:lvlRestart")
assert [paragraph._p.pPr.numPr.ilvl.val for paragraph in doc.paragraphs] == [
level for level, _ in code["ITEMS"]
]
Loading