使用Jinja2渲染字典或字符串

时间:2015-03-04 12:23:03

标签: python dictionary jinja2 cherrypy

我一直在尝试使用python字典呈现html模板。

实际上我为我的网页创建了一个站点地图,并使用{{%extends%}}标签实现了它。
我想要达到的解决方案是为每个网站创建一个字典,可以通过 CherryPy来访问并使用 Jinja 进行渲染。该过程如下:

  1. 我创建了一个包含所需变量的字典
  2. 将字典传递给一个额外的函数,该函数使用静态变量(sitemap)附加字典。
  3. 我尝试的第一个解决方案是将字典转换为字符串并返回字符串并进行渲染。


    import cherrypy
    import os
    from jinja2 import Environment, FileSystemLoader
    BASE_PATH = os.path.dirname(os.path.abspath(__file__))+"\\static"
    print BASE_PATH
    env = Environment(loader=FileSystemLoader(BASE_PATH))
    
    
    class Main(object):
        def __init__(self):
            self.sites = {"main": "index",
                          "leroy": "leroy"}
    
    def render_pages(self, template, dict):
        dictItemCount = len(dict)
        dictPosition = 1
        string=""
        for current in dict:
            if(dictPosition == dictItemCount):
                print 'last item in dictionary'
                string += str(current)+"="+"'"+str(dict[current])+"'"
                break
            dictPosition += 1
            string += str(current)+"="+"'"+str(dict[current])+"', "
        return template.render(>>>PROBLEM HERE<<<)
    
    @cherrypy.expose
    def leroy(self):
        tmpl = env.get_template('leroy.html')
        jahre = 24
        monate = jahre*12
        tage = monate*30
        stunden = tage*24
        minuten = stunden*60
        sekunden = minuten*60
        variables = {jahre: jahre,
                     monate: monate,
                     tage: tage,
                     stunden: stunden,
                     sekunden: sekunden}
        #tmpl.render(sites=self.sites, jahre=jahre, monate=monate, tage=tage, stunden=stunden, minuten=minuten, sekunden=sekunden)
        return Main.render_pages(self, tmpl, variables)
    
    cherrypy.quickstart(Main(), '/', "conf/cherrypy.conf")
    

    -------------------&GT;编辑&lt; -------------------

    以下是'leroy.html'模板:

        {% extends "base.html" %}
    {% block title %}{% endblock %}
    {% block head %}
        {{ super() }}
        <style type="text/css">
            .important { color: #336699; }
        </style>
    {% endblock %}
    {% block content %}
        <p class="important">
          Jahre: {{jahre}} <br  />
          Monate: {{monate}} <br  />
          Tage: {{tage}} <br  />
          Stunden: {{stunden}} <br  />
          Minuten: {{minuten}} <br  />
          Sekunden: {{ sekunden }}
        </p>
        <br  /><br  />
    {% endblock %}
    

    'base.html文件':

    {% block head %}
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>{% block title %}{% endblock %} - TEST </title>
    
        <!-- Bootstrap -->
        <link href="/static/css/bootstrap.css" rel="stylesheet">
    
        <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
          <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->
    
      </head>
    {% endblock %}
     {% block content %}
      <body>
     {% endblock %}
    
     {% block footer %}
          <br  /><br  />Sitemap:
          <ul id="sitemap">
             {% for site in sites %}
                <li><a href="/{{sites[site]}}">{{site}}</a></li>
             {% endfor %}
          </ul>
        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <!-- Include all compiled plugins (below), or include individual files as needed -->
        <script src="/static/js/bootstrap.min.js"></script>
    
      </body>
    </html>
    {% endblock %}
    

1 个答案:

答案 0 :(得分:1)

@jwalker的评论解决了我的问题:

  

您不需要将其转换为字符串,只需将字典传递给template.render()