简体   繁体   English

如何在 python 中使用 json 使用 jinja2 渲染模板?

[英]How to render templates with jinja2 using json in python?

I'm trying to directly load json data to render templates using jinja2 and I'm having trouble doing so without hardcoding values.我正在尝试使用 jinja2 直接加载 json 数据以呈现模板,并且在没有硬编码值的情况下我无法这样做。 For example,例如,

msg = template.render(posts=config[0]['context']['posts'])

Here, I've hardcoded the variable "posts" which exists in my json file and "config" is simply a python dict that I've loaded the json data into.在这里,我已经硬编码了存在于我的 json 文件中的变量“posts”,“config”只是一个 python 字典,我已经将 json 数据加载到其中。 Here's a snippet of the json file:这是 json 文件的片段:

[
  {
    "url": "/",
    "template": "index.html",
    "context": {
      "logname": "gjgk",
      "posts": [
        {
          "postid": "3",
          "owner": "ggkghj",
          "likes": 1,
          "comments": [
            {
              "owner": "dsf",
              "text": "#sadf"
            }
          ]
        }
]

If "posts" was named something else, how would I reflect this in my python code?如果“帖子”被命名为其他名称,我将如何在我的 python 代码中反映这一点? Should I change the variable names written in my template file?我应该更改模板文件中写入的变量名称吗?

Thanks谢谢

I figured out the solution.我想出了解决方案。 I used kwargs:我使用了 kwargs:

for x in config[0]['context']:
        msg = template.render(**{x:config[0]['context'][x]})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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