【问题标题】:How to render templates with jinja2 using json in python?如何在 python 中使用 json 渲染带有 jinja2 的模板?
【发布时间】:2020-10-07 14:46:25
【问题描述】:

我正在尝试使用 jinja2 直接加载 json 数据以呈现模板,但如果没有硬编码值,我会遇到麻烦。例如,

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

在这里,我已经硬编码了存在于我的 json 文件中的变量“posts”,而“config”只是一个我已将 json 数据加载到其中的 python dict。这是json文件的sn-p:

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

如果“帖子”被命名为其他名称,我将如何在我的 Python 代码中反映这一点?我应该更改模板文件中写入的变量名称吗?

谢谢

【问题讨论】:

  • 你能在帖子中添加模板吗?

标签: python json jinja2


【解决方案1】:

我想出了解决办法。我用过 kwargs:

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

【讨论】:

    猜你喜欢
    • 2017-03-01
    • 2018-07-29
    • 2014-12-23
    • 2018-06-05
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 2016-08-23
    • 2017-10-04
    相关资源
    最近更新 更多