简体   繁体   中英

Why does jinja isn't working for simple template

I am trying to create html document from html-template and python

Html template

<html>

<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
<meta name=Generator content="Microsoft Word 15 (filtered)">
<title>Договор подряда № 8/003-07 на выполнение проектных работ</title>
<style>
</style>

</head>
<body bgcolor=white lang=RU>
<div class=WordSection1>

<p class=MsoNormal align=center style='margin-right:-1.15pt;text-align:center'><b><span
style='font-size:12.0pt'>Договор подряда № {{document_number}}</span></b></p>

</div>
</body>
</html>

I want to fill **document_number ** but instead of value i have empty line "" How can I fix it?

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)
templateEnv = jinja2.Environment(
  loader=templateLoader,
  comment_start_string='{=',
  comment_end_string='=}',
)
template = templateEnv.get_template("income_contract_short.html")
sourceHtml = template.render(json_data=data_to_render) 

You're passing your data to template.render as json_data , so the only variable available to the template is json_data , which you have to access like a dictionary.

Option 1:
In the template, replace {{document_number}} with {{json_data['document_number']}}

Option 2:
Pass your data elements as separate keyword arguments to template.render, changing:
sourceHtml = template.render(json_data=data_to_render)
to
sourceHtml = template.render(document_number=data_to_render["document_number"], address=data_to_render["building_object_address"])
You could then access the building_object_address data as simply {{address}}.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM