我一直在尝试用python字典呈现html模板。在
实际上,我为我的网页创建了一个站点地图,并用{{%extends%}}
标记实现了它。
我想达到的解决方案是为每个网站创建一个字典,它可以用CherryPy访问,并用Jinja呈现。过程如下:
我尝试的第一个解决方案是将字典转换为字符串并返回字符串并呈现它。在
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")
------------------>;编辑<;------------
这是'勒罗伊.html'模板:
^{pr2}$'基本.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 %}
来自@jwalker的评论解决了我的问题:
相关问题 更多 >
编程相关推荐