Add jinja_env render option

This commit is contained in:
Eric Lapouyade 2016-02-11 15:09:55 +01:00
parent 4501b1d842
commit f446c47a0e
7 changed files with 29 additions and 6 deletions

View File

@ -1,3 +1,8 @@
0.1.10 (2016-2-11)
------------------
- render() accepts optionnal jinja_env argument :
useful to set custom filters and other things
0.1.9 (2016-1-18)
-----------------
- better subdoc management : accept tables

View File

@ -118,6 +118,21 @@ If you want to add dynamically changeable style, you have to use both : the `{{r
You can change color, bold, italic, size and so on, but the best way is to use Microsoft Word to define your own *caracter* style
( Home tab -> modify style -> manage style button -> New style, select Character style in the form ), see exemple in `tests/richtext.py`
Jinja custom filters
--------------------
``render()`` accepts ``jinja_env`` optionnal argument : you may pass a jinja environment object.
By this way you will be able to add some custom jinja filters::
from docxtpl import DocxTemplate
import jinja2
doc = DocxTemplate("my_word_template.docx")
context = { 'company_name' : "World company" }
jinja_env = jinja2.Environment()
jinja_env.filters['myfilter'] = myfilterfunc
doc.render(context,jinja_env)
doc.save("generated_doc.docx")
Examples
--------

View File

@ -59,16 +59,19 @@ class DocxTemplate(object):
return src_xml
def render_xml(self,src_xml,context):
template = Template(src_xml)
def render_xml(self,src_xml,context,jinja_env=None):
if jinja_env:
template = jinja_env.from_string(src_xml)
else:
template = Template(src_xml)
dst_xml = template.render(context)
dst_xml = dst_xml.replace('{_{','{{').replace('}_}','}}').replace('{_%','{%').replace('%_}','%}')
return dst_xml
def build_xml(self,context):
def build_xml(self,context,jinja_env=None):
xml = self.get_xml()
xml = self.patch_xml(xml)
xml = self.render_xml(xml, context)
xml = self.render_xml(xml, context, jinja_env)
return xml
def map_xml(self,xml):
@ -76,8 +79,8 @@ class DocxTemplate(object):
body = root.body
root.replace(body,etree.fromstring(xml))
def render(self,context):
xml = self.build_xml(context)
def render(self,context,jinja_env=None):
xml = self.build_xml(context,jinja_env)
self.map_xml(xml)
def new_subdoc(self):

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.