Search code examples
pythonhtmljinja2html-email

Will \n in jinja2 templates create a problem?


I am creating a table using jinja2 template. When I start to write all the html code in a single line, it breaks the table sent via email.

So I am writing

table_row = '<tr>\
                    <td>{{dev}}</td>\
                    <td>{{pr_count}}</td>\
                </tr>'
table_row_template = jinja2.Template(table_row)

In a big loop, I start appending the data to the the table using the row template.

for developer in developer_json:
     dev_count_list = dev_count_list\
                     + table_row_template.render(dev = dev_count[0], pr_count = dev_count[1]) + '\n'

Finally when I render using dev_count_list inside a base template, everything works fine.

My question - How is \n interpreted by jinja2 template. Will it add a new line or just writes \n again


Solution

  • Consider this minimal example:

    t = Template("Hello \n{{ something }}!")
    output = t.render(something="World")
    print(output)
    for b in bytearray(output, 'ascii'):
        print(b, chr(b))
    

    This yields the rendered string byte-by-byte:

    Hello 
    World!
    72 H
    101 e
    108 l
    108 l
    111 o
    32  
    10 
    
    87 W
    111 o
    114 r
    108 l
    100 d
    33 !
    

    So as you can see, the \n character (LF, 10 decimal) is preserved when rendering the output string.