I would like to seek your help on my below issue. I have been struggling with this issue for a few days.
I have a word template as shown below in docx.
===============
Name: {{ Personal_name }}
Age:{{ Personal_Age }}
Teenager/Adult: {% if Personal_Age ==18 %}
Teenager
{% else %}
Adult
{% endif %}
It is expected that the "Teenager/Adult" value should be "Teenager" as per the conditional statement. However, the value is still showing "Adult", which indicates the conditional statement does not work. Would everyone let me know what is the issue on it?
Also, does everyone let me know how to turn the "Age" background colour to be red with a comment box pop up if there is null input in "Age"?
Here is my scripts for your reference as well.
========================================================
from docxtpl import DocxTemplate,RichText
doc=DocxTemplate('test_word_2.docx')
context={'Personal_name':'Charlie','Personal_Age':RichText(18,color='FF0000',bold=True)}
doc.render(context)
doc.save('test_word_2_test'+'.docx')
===================================================
The current final output is attached here
Thanks everyone.
An equals check between RichText
and int
will always be false since they are different types and no __eq__
override exists for checking against the text content. RichText source code
Plus it seems like there is no easy way to get the RichText
content.
Easiest solution is adding a new context variable for programmatic handling while keeping the RichText
for display:
Edit: I did not change the logic, but it seems like you want to check < 18
since from age 18 you are an adult?
from docxtpl import DocxTemplate,RichText
doc = DocxTemplate('test_word_2.docx')
personal_age = 18
context = {
'Personal_name': 'Charlie',
'Personal_Age': RichText(personal_age, color='FF0000', bold=True),
'Personal_Age_int': personal_age
}
doc.render(context)
doc.save('test_word_2_test'+'.docx')
Name: {{ Personal_name }}
Age:{{ Personal_Age }}
Teenager/Adult: {% if Personal_Age_int == 18 %}
Teenager
{% else %}
Adult
{% endif %}