1

I'm trying to directly load json data to render templates using jinja2 and I'm having trouble doing so without hardcoding values. 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. Here's a snippet of the json file:

[
  {
    "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? Should I change the variable names written in my template file?

Thanks

1
  • Can you add template to the post. Commented Jun 17, 2020 at 17:25

1 Answer 1

1

I figured out the solution. I used kwargs:

for x in config[0]['context']:
        msg = template.render(**{x:config[0]['context'][x]})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.