python bottle - why is the simple template engine turning my dict into a list?
Question
I'm calling the template in the following route:
page = {"name": "welcome", "title": "Welcome", "icon": "/images/welcome-icon.png"}
contentOnly = request.query.get("contentOnly")
formRedirect = False
admin = is_admin()
announcments = get_announcments()
page = ""
if contentOnly:
page += template("./views/welcome.tpl", contentOnly = contentOnly, announcments = announcments)
else:
page += template("./views/header.tpl", page = page, admin = admin)
page += template("./views/welcome.tpl", contentOnly = contentOnly, announcments = announcments)
page += template("./views/footer.tpl", formRedirect = formRedirect)
When it hits this line in header.tpl:
%if page['name'] == "welcome":
It throws the following error:
File "/home/brett/projects/tastech website/development/views/header.tpl", line 5, in <module>
%if page['name'] == "welcome":
TypeError: string indices must be integers
Solution
You set page
to an empty string, before calling the template:
page = ""
# ...
else:
page += template("./views/header.tpl", page = page, admin = admin)
So within the template, page
is set to ""
, the empty string.
Use a different name for the dictionary; page_data
, perhaps:
page_data = {"name": "welcome", "title": "Welcome", "icon": "/images/welcome-icon.png"}
# ...
page = ""
# ...
else:
page += template("./views/header.tpl", page=page_data, admin=admin)
OTHER TIPS
You set page = ""
. So page is a string. Then you pass page
to header.tpl
. Well, it's a string, and you can't index into a string with another string.
Solution: use a different name for your string than for your dict.
You've overwritten the original dictionary called page
with another variable, which is a string consisting of the concatenated template results. Call that something else.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow