Skip to content

how to make template to detect empty richtext fields #600

Open

Description

@abubelinha

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

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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions