【问题标题】:Render Dictionary or String with Jinja2使用 Jinja2 渲染字典或字符串
【发布时间】:2015-05-05 10:33:26
【问题描述】:

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

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

  1. 我创建了一个包含所需变量的字典
  2. 将字典传递给一个额外的函数,该函数将静态变量(站点地图)附加到字典中。

我尝试的第一个解决方案是将字典转换为字符串并返回字符串并渲染它。


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")

-------------------> 编辑

这是 '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 %}

【问题讨论】:

  • 你能添加一个你期望呈现的例子吗?
  • 看看this answer的Jinja2工具。
  • 你不需要将其转换为字符串,只需将 dict 传递给 template.render()。

标签: python dictionary jinja2 cherrypy


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-10-09
    • 2018-07-29
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2014-08-09
    • 2022-07-09
    • 1970-01-01
    相关资源
    最近更新 更多