Search code examples
pythonjinja2

jinja2.exceptions.TemplateSyntaxError: Missing end of comment tag


I am trying to create a html file from my html-template with help of python and jinja2 lib

My file https://drive.google.com/file/d/1Z4_Xso7eyR9thXdqnntNncd07jrRNHHY/view?usp=sharing My code:

import jinja2  # create html files

templateLoader = jinja2.FileSystemLoader(
    searchpath="./"
)
data_to_render = {
    "document_number": "123",
    "building_object_address": "Moscow"
}
templateEnv = jinja2.Environment(loader=templateLoader)
template = templateEnv.get_template("income_contract_web.html")
sourceHtml = template.render(json_data=data_to_render) 

with open("xyz_result.html", "w") as f:
    f.write(sourceHtml)

I have this error:

 File "/home/alex/root_folder/projects/61_documents/1_documents_template/jinja_html/src.py", line 14, in <module>
    template = templateEnv.get_template("income_contract_web.html")
    .......

    raise rewrite_traceback_stack(source=source)
  File "<unknown>", line 13, in template
jinja2.exceptions.TemplateSyntaxError: Missing end of comment tag

I think that error deals with this line:

*/#sidebar{position:absolute;top

Are there settings in jinja to process this line?


Solution

  • The source of the problem is the inlined, minimized CSS that targets an id, like: {#sidebar{ or {#sidebar.opened+#page-container{. By default Jinja2 uses {# for comments, so it tries to find the closing tag #}. However you can choose a different string for these tags, e.g.:

    templateEnv = jinja2.Environment(
      loader=templateLoader,
      comment_start_string='{=',
      comment_end_string='=}',
    )
    

    Alternatively, you can put these CSS into an external file.