### Install python-docx-template with pip Source: https://docxtpl.readthedocs.io/en/latest/index.html Use this command to install the library using pip. ```bash pip install docxtpl ``` -------------------------------- ### Basic Usage of DocxTemplate Source: https://docxtpl.readthedocs.io/en/latest/index.html This example shows how to load a template, provide context, render the document, and save the generated file. ```python from docxtpl import DocxTemplate doc = DocxTemplate("my_word_template.docx") context = { 'company_name' : "World company" } doc.render(context) doc.save("generated_doc.docx") ``` -------------------------------- ### Install python-docx-template with conda Source: https://docxtpl.readthedocs.io/en/latest/index.html Use this command to install the library using conda. ```bash conda install docxtpl --channel conda-forge ``` -------------------------------- ### Setting up Docxtpl Environment with Pipenv Source: https://docxtpl.readthedocs.io/en/latest/index.html Install Pipenv if you haven't already, then use it to install dependencies for the docxtpl project, activate the shell, and run the tests. This ensures a consistent Python environment. ```bash pip install pipenv (if not already done) cd python-docx-template (where Pipfiles are) pipenv install --python 3.6 -d pipenv shell cd tests/ python runtests.py ``` -------------------------------- ### Merge DOCX as Sub-document Source: https://docxtpl.readthedocs.io/en/latest/index.html Merge an existing .docx file as a sub-document into your template. This requires installing the 'subdoc' extra. The sub-document content is inserted where the template variable is declared. ```python tpl = DocxTemplate('templates/merge_docx_master_tpl.docx') sd = tpl.new_subdoc('templates/merge_docx_subdoc.docx') context = { 'mysubdoc': sd, } tpl.render(context) tpl.save('output/merge_docx.docx') ``` -------------------------------- ### Get Undeclared Template Variables Source: https://docxtpl.readthedocs.io/en/latest/index.html Retrieve a set of variables that are present in the template but not provided in the context. If no context is passed, it returns all variables needed for full rendering. ```python tpl=DocxTemplate('your_template.docx') tpl.render(context_dict) set_of_variables = tpl.get_undeclared_template_variables(context=context_dict) ``` -------------------------------- ### Replace Embedded Object by Zipname Source: https://docxtpl.readthedocs.io/en/latest/index.html For embedded objects other than docx (like Excel or PowerPoint files), use `replace_zipname` by specifying the object's path within the docx's zip structure. The zipname typically starts with 'word/embeddings/'. This method is useful when `replace_embedded` may not work. ```python tpl.replace_zipname( 'word/embeddings/Feuille_Microsoft_Office_Excel1.xlsx', 'my_excel_file.xlsx') ``` -------------------------------- ### Run Tests with Pipenv Source: https://docxtpl.readthedocs.io/en/latest/_sources/index.rst Set up a Python environment using Pipenv and run the test suite for the docx-template library. This is useful for verifying the library's functionality in a controlled environment. ```bash pip install pipenv (if not already done) cd python-docx-template (where Pipfiles are) pipenv install --python 3.6 -d pipenv shell cd tests/ python runtests.py ``` -------------------------------- ### Running Docxtpl Test Suite Source: https://docxtpl.readthedocs.io/en/latest/index.html Navigate to the tests directory and execute the runtests.py script to generate final docx files from test templates. Generated files will be in the tests/output directory. ```bash cd tests/ python runtests.py ``` -------------------------------- ### Command-line Usage for Docxtpl Source: https://docxtpl.readthedocs.io/en/latest/index.html Use this command to generate a docx file from a template and a JSON context file directly from your terminal. Options include overwriting existing files and suppressing output. ```bash usage: python -m docxtpl [-h] [-o] [-q] template_path json_path output_filename Make docx file from existing template docx and json data. positional arguments: template_path The path to the template docx file. json_path The path to the json file with the data. output_filename The filename to save the generated docx. optional arguments: -h, --help show this help message and exit -o, --overwrite If output file already exists, overwrites without asking for confirmation -q, --quiet Do not display unnecessary messages ``` -------------------------------- ### Replace Media in Docx Template Source: https://docxtpl.readthedocs.io/en/latest/index.html Use `replace_media` to swap a dummy media file in your template with a new one. The dummy file must exist in the template directory during rendering and saving. This method works for images in headers, footers, and the document body. ```python tpl.replace_media('dummy_header_pic.jpg','header_pic_i_want.jpg') ``` -------------------------------- ### Add Custom Jinja Filters for Rendering Source: https://docxtpl.readthedocs.io/en/latest/index.html Extend Jinja's capabilities by adding custom filters to the environment. This allows for more complex logic within your templates, such as custom calculations. ```python from docxtpl import DocxTemplate import jinja2 def multiply_by(value, by): return value * by doc = DocxTemplate("my_word_template.docx") context = { 'price_dollars' : 5.00 } jinja_env = jinja2.Environment() jinja_env.filters['multiply_by'] = multiply_by doc.render(context,jinja_env) doc.save("generated_doc.docx") ``` ```jinja Euros price : {{ price_dollars|multiply_by(0.88) }} ``` -------------------------------- ### Add Custom Jinja Filters Source: https://docxtpl.readthedocs.io/en/latest/_sources/index.rst Pass a Jinja environment object to the render() method to add custom filters. This allows for extended template logic beyond standard Jinja features. ```python from docxtpl import DocxTemplate import jinja2 def multiply_by(value, by): return value * by doc = DocxTemplate("my_word_template.docx") context = { 'price_dollars' : 5.00 } jinja_env = jinja2.Environment() jinja_env.filters['multiply_by'] = multiply_by doc.render(context,jinja_env) doc.save("generated_doc.docx") ``` -------------------------------- ### RichText with Hyperlink Source: https://docxtpl.readthedocs.io/en/latest/_sources/index.rst Add hyperlinks to text using `RichText.add()`. The `url_id` parameter is generated using `tpl.build_url_id()`. Render the `RichText` object in the template using `{{r rt}}`. ```python rt = RichText('You can add an hyperlink, here to ') rt.add('google',url_id=tpl.build_url_id('http://google.com')) ``` -------------------------------- ### Displaying Jinja2 Variables Source: https://docxtpl.readthedocs.io/en/latest/index.html Standard Jinja2 double braces for variable display. Special characters like \n, \a, \t, and \f are translated. For RichText objects, use {{r }} to specify a new run. ```jinja2 {{ }} ``` ```jinja2 {{r }} ``` -------------------------------- ### Replacing Dummy Pictures in DOCX Source: https://docxtpl.readthedocs.io/en/latest/index.html Replace dummy pictures in your DOCX template with new images. This method works for headers, footers, and the main document body, maintaining the aspect ratio of the original image. Specify the base name of the image file used in the template. ```python tpl.replace_pic('dummy_header_pic.jpg','header_pic_i_want.jpg') ``` -------------------------------- ### Add Hyperlink with RichText Source: https://docxtpl.readthedocs.io/en/latest/index.html Create a RichText object and add a hyperlink to a specific URL using the build_url_id method. This allows for clickable links within your document. ```python tpl=DocxTemplate('your_template.docx') rt = RichText('You can add an hyperlink, here to ') rt.add('google',url_id=tpl.build_url_id('http://google.com')) ``` -------------------------------- ### Add Inline Image to Template Source: https://docxtpl.readthedocs.io/en/latest/index.html Create an InlineImage object to dynamically add images to your document. Specify the template, image path, and optionally dimensions using Mm, Inches, or Pt classes. ```python myimage = InlineImage(tpl, image_descriptor='test_files/python_logo.png', width=Mm(20), height=Mm(10)) ``` -------------------------------- ### Replace Embedded Docx in Template Source: https://docxtpl.readthedocs.io/en/latest/index.html Use `replace_embedded` to replace a dummy embedded document (e.g., another docx) with a new file. Similar to `replace_media`, the dummy file must exist in the template directory. This method is primarily for embedded docx files. ```python tpl.replace_embedded('embedded_dummy.docx','embedded_docx_i_want.docx') ``` -------------------------------- ### Jinja2 Tags for Docx Structure Management Source: https://docxtpl.readthedocs.io/en/latest/index.html Use these tags to manage paragraphs, table rows, table columns, and runs within your templates. These tags also instruct python-docx-template to remove the element they are in. ```jinja2 {%p jinja2_tag %} for paragraphs {%tr jinja2_tag %} for table rows {%tc jinja2_tag %} for table columns {%r jinja2_tag %} for runs ``` -------------------------------- ### Preserve Spaces and Tabs with RichText Source: https://docxtpl.readthedocs.io/en/latest/_sources/index.rst For Microsoft Word 2016, use RichText to preserve leading spaces and tabulations that would otherwise be ignored. Apply this when spaces or tabs at the beginning of a line are critical. ```python tpl.render({ 'test_space_r' : RichText(' '), 'test_tabs_r': RichText(5*' '), }) ``` -------------------------------- ### Setting Table Cell Background Color Source: https://docxtpl.readthedocs.io/en/latest/index.html Use the `{% cellbg %}` tag at the beginning of a cell to set its background color. The variable must be a hexadecimal color code without the hash sign. ```jinja2 {% cellbg %} ``` -------------------------------- ### Jinja2 Run Tag Syntax Source: https://docxtpl.readthedocs.io/en/latest/_sources/index.rst Use the {%r ... %} tag to conditionally include or exclude entire runs (sequences of characters with the same style) within a paragraph in your generated document. The tag itself will be removed from the final output. ```jinja {%r jinja2_tag %} ``` -------------------------------- ### Specify Regional Font with RichText Source: https://docxtpl.readthedocs.io/en/latest/index.html Use this to specify a font for a particular region when the default font is not displayed correctly. Prefix the font name with the region and a colon. ```python ch = RichText('测试TEST', font='eastAsia:微软雅黑') ``` -------------------------------- ### Splitting and Merging Text with Jinja2 Tags Source: https://docxtpl.readthedocs.io/en/latest/index.html Use `{%-` and `-%}` to merge Jinja2 tags across lines, allowing for better readability of long template sections. Ensure these tags are on their own lines. ```jinja2 {%- if living_in_town -%} in urban area {%- else -%} in countryside {%- endif -%} ``` -------------------------------- ### Escaping Jinja2 Delimiters Source: https://docxtpl.readthedocs.io/en/latest/_sources/index.rst To display literal Jinja2 delimiters like `{%` or `{{`, use escaped versions: `{_%` for `{%`, `%_}` for `%}`, `{_{` for `{{`, and `}_}` for `}}`. ```jinja2 {_% , %_}, {_{ or }_} ``` -------------------------------- ### Escaping Special Characters in Templates Source: https://docxtpl.readthedocs.io/en/latest/_sources/index.rst Handle special XML characters like '<', '>', and '&' within template variables. Choose from multiple escaping methods or enable autoescaping during rendering. ```python context = { 'var':R('my text') } ``` ```python context = { 'var':'my text'} ``` ```python context = { 'var':escape('my text')} ``` ```python tpl.render(context, autoescape=True) ``` -------------------------------- ### Jinja2 Tag Merging Source: https://docxtpl.readthedocs.io/en/latest/_sources/index.rst Use `{%-` to merge a Jinja2 tag with the previous line and `-%}` to merge with the next line. This is useful for creating more readable templates with Jinja2 tags. ```jinja2 {#p this is a comment as a paragraph #} {#tr this is a comment as a table row #} {#tc this is a comment as a table cell #} ``` ```jinja2 {% if living_in_town %} in urban area {% else %} in countryside {% endif %} ``` ```jinja2 {%- if living_in_town -%} in urban area {%- else -%} in countryside {%- endif -%} ``` -------------------------------- ### Escaping Jinja2 Delimiters Source: https://docxtpl.readthedocs.io/en/latest/index.html Display literal Jinja2 delimiters like `{%`, `%}`, `{{`, or `}}` in your document by using escaped sequences. ```jinja2 {_%, %_}, {_{ or }_} ``` -------------------------------- ### Jinja2 Comment Syntax Source: https://docxtpl.readthedocs.io/en/latest/_sources/index.rst Use Jinja2 comment syntax {# ... #} to add comments within your Word document template. These comments will not appear in the generated document. ```jinja {# ... #} ``` -------------------------------- ### Replacing Embedded ZIP Archives (e.g., Excel) Source: https://docxtpl.readthedocs.io/en/latest/_sources/index.rst Replace embedded objects that are not DOCX files, such as embedded Excel spreadsheets, by specifying their internal path within the DOCX structure. This method is used when `replace_embedded()` is not suitable. ```python tpl.replace_zipname( 'word/embeddings/Feuille_Microsoft_Office_Excel1.xlsx', 'my_excel_file.xlsx') ``` -------------------------------- ### Conditional Paragraph Removal with Jinja2 Source: https://docxtpl.readthedocs.io/en/latest/index.html Demonstrates how to conditionally remove paragraphs using {%p ... %} tags. The outer paragraphs containing the {%p ... %} tags are always removed, regardless of the condition. ```jinja2 {%p if display_paragraph %} One or many paragraphs {%p endif %} ``` -------------------------------- ### Table Cell Spanning with Colspan Source: https://docxtpl.readthedocs.io/en/latest/index.html Use the `colspan` tag to horizontally span table cells. The argument must be an integer representing the number of columns to span. ```jinja2 {% colspan %} ``` -------------------------------- ### Escaping Special Characters with Listing Class Source: https://docxtpl.readthedocs.io/en/latest/index.html Use the Listing class to escape text and manage newlines, paragraph breaks, and special characters when including listings in your document. The character styling is preserved except after a paragraph break. ```python context = { 'mylisting':Listing('the listing with some lines  and some paragraph  and special chars : <>&') } ``` -------------------------------- ### Horizontal and Vertical Cell Merging in Tables Source: https://docxtpl.readthedocs.io/en/latest/index.html Tags for merging cells within loops. `{% hm %}` merges cells horizontally, and `{% vm %}` merges cells vertically. ```jinja2 {% hm %} ``` ```jinja2 {% vm %} ``` -------------------------------- ### Jinja2 Comments for Docx Structure Source: https://docxtpl.readthedocs.io/en/latest/index.html Add comments to your template that correspond to specific document elements like paragraphs, table rows, or table cells. These comments are ignored during generation. ```jinja2 {#p this is a comment as a paragraph #} {#tr this is a comment as a table row #} {#tc this is a comment as a table cell #} ``` -------------------------------- ### Table Cell Spanning and Merging Source: https://docxtpl.readthedocs.io/en/latest/_sources/index.rst Control table cell behavior using Jinja2 tags. `colspan` spans cells horizontally, `hm` merges cells horizontally within a loop, and `vm` merges cells vertically within a loop. ```jinja2 {% colspan %} ``` ```jinja2 {% hm %} ``` ```jinja2 {% vm %} ``` -------------------------------- ### Jinja2 Table Column Tag Syntax Source: https://docxtpl.readthedocs.io/en/latest/_sources/index.rst Use the {%tc ... %} tag to conditionally include or exclude entire table columns in your generated document. The tag itself will be removed from the final output. ```jinja {%tc jinja2_tag %} ``` -------------------------------- ### Jinja2 Table Row Tag Syntax Source: https://docxtpl.readthedocs.io/en/latest/_sources/index.rst Use the {%tr ... %} tag to conditionally include or exclude entire table rows in your generated document. The tag itself will be removed from the final output. ```jinja {%tr jinja2_tag %} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.