Skip to content

how to make template to detect empty richtext fields #138

Done

Description

@cvas22

Copied from python-docx-template issue 600, opened by @abubelinha on 2025-06-16.


Hello.
I am trying to do something like this for each entry (e) in my template:

{% for e in entries %}
{{ e.country }}: {{ e.locality }}{%r if e.habitat %}; {{r e.habitat }}{%r endif %}{% if e.substrate %}; {{ e.substrate }}{% endif %}.
{% endfor %}

Basically, I want habitat & substrate fields to be printed preceded by a separator ';' (but ONLY if those fields contain a text; otherwise, the separator and field shouldn't be printed).

from docxtpl import DocxTemplate, RichText as RT
from docx import Document
tpl = DocxTemplate("template.docx")
context = {"entries": [
	{"country":"USA", "locality":"Boston", "habitat":"forest", "substrate":"wood"}, 
	{"country":"USA", "locality":"New Orleans", "habitat":"marsh", "substrate":""}, 
	{"country":"USA", "locality":"Honolulu", "habitat":RT("", color="blue"), "substrate":"water"}, 
	{"country":"USA", "locality":"St. Louis", "habitat":RT("ship", color="blue"), "substrate":"water"}, 
	{"country":"USA", "locality":RT("New York!", color="ff0000"), "habitat":"", "substrate":"concrete"}
]}
tpl.render(context, autoescape=True)
tpl.save("filled-template.docx")

This is a simplified version of my code (I generate my context from a database and I apply RichText using a function depending on some other factors).
But the Honolulu entry illustrates my problem: is there a way my template can detect that RT("", color="blue") is actually an empty text entry, so the {%r if e.habitat %} should not be executed?

Currently, I am getting this text output (I am not showing the bold/italics/coloured output here, since that's not the problem: please notice the double ; separator after Honolulu):

USA: Boston; forest; wood.
USA: New Orleans; marsh.
USA: Honolulu; ; water.
USA: St. Louis; ship; water.
USA: New York!; concrete.

Activity

  1. cvas22 commented on Nov 25, 2026

    @cvas22
    OwnerAuthor

    @abubelinha an empty RichText is now falsy, so {%r if e.habitat %} skips RT("", color="blue") the same way it skips "", and the Honolulu line loses the extra ;. Fixed in #205, it'll be in the next release, or pip install git+https://github.com/cvas22/docform to try it now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions