{"id":3468,"library":"docxtpl","title":"docxtpl","description":"docxtpl is a Python library that serves as a docx template engine, enabling the generation of Word documents from templates enhanced with Jinja2-like tags. It leverages `python-docx` for document manipulation and `jinja2` for templating logic. The current version is 0.20.2, and it appears to be actively maintained with regular updates.","status":"active","version":"0.20.2","language":"en","source_language":"en","source_url":"https://github.com/elapouya/python-docx-template","tags":["docx","template","word","jinja2","reporting","document-generation","automation"],"install":[{"cmd":"pip install docxtpl","lang":"bash","label":"PyPI"},{"cmd":"conda install docxtpl --channel conda-forge","lang":"bash","label":"Conda-forge"}],"dependencies":[{"reason":"Used for the templating syntax within the .docx documents.","package":"jinja2","optional":false},{"reason":"Required for XML parsing of .docx files.","package":"lxml","optional":false},{"reason":"Core library for reading, writing, and creating Word documents and sub-documents.","package":"python-docx","optional":false},{"reason":"Extra dependency required for advanced sub-document features. Install with 'pip install \"docxtpl[subdoc]\"'.","package":"subdoc","optional":true}],"imports":[{"symbol":"DocxTemplate","correct":"from docxtpl import DocxTemplate"},{"symbol":"InlineImage","correct":"from docxtpl import InlineImage"},{"note":"Can also be imported as 'R'.","symbol":"RichText","correct":"from docxtpl import RichText"},{"note":"Can also be imported as 'RP'.","symbol":"RichTextParagraph","correct":"from docxtpl import RichTextParagraph"},{"note":"Used for specifying dimensions (e.g., image width/height). Also 'Inches' and 'Pt' are available.","symbol":"Mm","correct":"from docx.shared import Mm"}],"quickstart":{"code":"import os\nfrom docxtpl import DocxTemplate\n\n# Create a dummy template file for demonstration\ndummy_template_content = (\n    \"Hello {{ name }},\\n\"\n    \"This is a test document generated by docxtpl.\\n\"\n    \"Your company: {{ company_name }}.\\n\"\n)\nwith open(\"my_word_template.docx\", \"w\") as f:\n    # In a real scenario, this would be a proper .docx file with Jinja2 tags\n    # For a runnable quickstart, we'll simulate a simple text file\n    f.write(dummy_template_content)\n\n# Path to your Word template file (e.g., 'my_word_template.docx')\ntemplate_path = \"my_word_template.docx\"\noutput_path = \"generated_doc.docx\"\n\n# Ensure the template file exists (in a real scenario, it's a pre-made .docx)\nif not os.path.exists(template_path):\n    # For a real .docx, you would create it in MS Word\n    print(f\"Please create a real .docx template named '{template_path}' with {{ name }} and {{ company_name }} tags.\")\n    # Exit or handle error if the template doesn't exist\n    exit(1)\n\n# Load the template\ndoc = DocxTemplate(template_path)\n\n# Define the context (data to fill into the template)\ncontext = {\n    'name': 'World',\n    'company_name': 'Example Inc.'\n}\n\n# Render the document with the context\ndoc.render(context)\n\n# Save the generated document\ndoc.save(output_path)\n\nprint(f\"Generated document saved to {output_path}\")\n\n# Clean up the dummy file (optional)\n# os.remove(template_path)\n# os.remove(output_path)","lang":"python","description":"This quickstart demonstrates how to load a .docx template, provide a dictionary of context variables, render the template, and save the generated document. The template itself would be a standard .docx file created in Microsoft Word, containing Jinja2-like placeholders such as `{{ variable_name }}`."},"warnings":[{"fix":"Use the appropriate `p`, `tr`, `tc`, or `r` prefixed tags for structural control (paragraph, table row, table cell, run). Consult the official documentation for examples on splitting long text or table loops with these tags.","message":"Jinja2 tag placement is crucial. Standard `{{ }}` tags must reside within a single 'run' of text in a paragraph. For controlling entire paragraphs, table rows, or cells, special tags like `{%p ... %}`, `{%tr ... %}`, `{%tc ... %}` respectively are required. Incorrect placement often leads to unexpected rendering or content being crammed.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Pre-process `RichText` content in Python. For example, `context = {'my_text': RichText(my_raw_text.lower())}` instead of `{{r my_text|lower }}` in the template.","message":"RichText objects are not compatible with Jinja2 filters directly within the template. If you need to apply formatting or transformations to `RichText` content, perform these operations in your Python code *before* passing the `RichText` object to the template context.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Place the `{%tr for ... %}` tag in the first cell of the row to be repeated and the `{%tr endfor %}` tag in the last cell of that same row. The documentation provides examples for proper table looping.","message":"When working with loops in tables (`{%tr for item in items %}`), ensure the loop tags correctly span the cells of the row you intend to duplicate. Incorrect placement can cause all iterated data to appear in a single cell instead of generating new rows.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Use Jinja2's whitespace control characters `{%-` and `-%}` to strip whitespace around blocks. For explicit spaces at line beginnings or endings in the Word document, use an unbreakable space (Ctrl+Shift+Space in Microsoft Word).","message":"Controlling whitespace when using conditional or loop tags can be tricky. Unwanted spaces might appear if not handled correctly.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Upgrade to `docxtpl` version 0.15.1 or newer to enable reliable multi-rendering with a single `DocxTemplate` object. If upgrading is not possible, ensure all context is provided in a single `render()` call.","message":"Prior to version 0.15.1, calling `render()` multiple times on the same `DocxTemplate` object could lead to loss of unresolved variables, making multi-step rendering problematic.","severity":"breaking","affected_versions":"< 0.15.1"}],"env_vars":null,"last_verified":"2026-04-11T00:00:00.000Z","next_check":"2026-07-10T00:00:00.000Z"}