Rendering a python dict in Jinja2 / Werkzeug

前端 未结 3 1426
梦谈多话
梦谈多话 2020-12-15 04:00

I\'m playing with a url shortener (basing it on the Shortly demo app from Werkzeug).

I have a dict like this -

    (\'1\', {\'target\': \'http://10.         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-15 04:39

    One approach is to cleanly separate processing logic from the HTML. Thus, put HTML in a separate file, such as, top.reddit.html. But content within the HTML is dynamic since it's pulled from Reddit. So we use Jinja2 as the templating engine. This implies that top.reddit.html is just the template but not the final content to be served.

    top.reddit.html (showing only the dynamic rows here for brevity):

    {% for item in data %}
    
       
      {{item["date"]}}, {{item["title"]}}
    {{item["teaser"]}}   {% endfor %}

    Python code to render the template (tested with Python 3.5.6, Jinja2 2.10):

    import jinja2
    
    # For illustration: list of dict
    top_posts = [
        {'date': '06 Jun, 11:40AM', 'title': 'Title 1 goes here',  'teaser': 'One blah blah blah...'},
        {'date': '05 Jun, 04:50PM', 'title': 'Title 2 goes here',  'teaser': 'Two blah blah blah...'},
        {'date': '05 Jun, 09:60AM', 'title': 'Title 3 goes here',  'teaser': 'Three blah blah blah...'}
    ]
    
    loader = jinja2.FileSystemLoader(searchpath="./")
    jenv = jinja2.Environment(loader=loader)
    template = jenv.get_template('top.reddit.html')
    htmlout = template.render(data=top_posts)
    print(htmlout)
    

提交回复
热议问题