Jinja and non-ASCII characters (was Re: Prepare accented characters for HTML)

Chris Angelico rosuav at gmail.com
Thu Mar 28 14:04:36 EDT 2019


On Fri, Mar 29, 2019 at 4:10 AM Tony van der Hoff <lists at vanderhoff.org> wrote:
>
> This'll probably work:
>
> accent-test/accent-test.py:
> #####################################################################
> #!/usr/bin/env python3
>
> import os
> from jinja2 import Environment, FileSystemLoader
>
> PATH = os.path.dirname(os.path.abspath(__file__))
> TEMPLATE_ENVIRONMENT = Environment(
>     autoescape=False,
>     loader=FileSystemLoader(os.path.join(PATH, 'templates')),
>     trim_blocks=False)
>
>
> def render_template(template_filename, context):
>     return
> TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)
>
>
> def create_index_html():
>
>     # put the list into a dictionary for rendering
>     context = {
>                 'title': "accent-test",
>                 'french': 'année',
>                 'french1': 'année',
>               }
>
>     # render the template to html
>     print ("Content-type: text/html\n\n")
>     print (render_template('accent-test.jnj', context))
>
> def main():
>     create_index_html()
>
> ########################################
>
> if __name__ == "__main__":
>     main()
> #####################################################################
>
> accent-test/templates/accent-test.jnj:
>
> #####################################################################
> <!DOCTYPE html>
> <html>
>   <head>
>     <meta charset="utf-8"/>
>     <title>{{title}}</title>
>   </head>
>   <body>
>     <center>
>       <h1>{{title}}</h1>
> {#
>       <p>{{french}}</p>
> #}
>       <p>{{french1}}</p>
>     </center>
>   </body>
> </html>
>
> #####################################################################

Well, I just tried this, and it worked fine (even after uncommenting
the 'french' line). Gave me this output:

Content-type: text/html


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
    <title>accent-test</title>
  </head>
  <body>
    <center>
      <h1>accent-test</h1>
      <p>année</p>
      <p>année</p>
    </center>
  </body>
</html>

You have a python3 shebang, but are you definitely running this under Python 3?

Here's a much more minimal example. Can you see if this also fails for you?

import sys
from jinja2 import Template
print(Template("French: {{french}}").render({"french": "année"}))
print(sys.version)

ChrisA



More information about the Python-list mailing list