簡體   English   中英

Jinja2:如何呈現字典| UndefinedError

[英]Jinja2: HOW-TO render a dict | UndefinedError

我將模板.html存儲在變量“ email_html”中,也將一個名為“ info”的字典定義為

info = {'username': u'snip', 'netlink': [u'> F: IL00091 = AMS/VIE/LE-134621 : None : None | O: at-vie01a- : xe-3/1/3 _ et-2/1/21 : nl-ams05a- | W: None : None _ None : None *'], 'end': [2015, 8, 15, 11], 'notes': u'', 'usms': u'ccc', 'start': [2015, 8, 15, 11], 'netelement': [u'> at-vie01a- * x.x.x.x']}

但是當我嘗試將info變量加載到模板時:

template = jinja2.Template(open(email_html).read())
html = template.render(**info)

正在收到以下錯誤:

In [13]: html = template.render(**info)
---------------------------------------------------------------------------
UndefinedError                            Traceback (most recent call last)
<ipython-input-13-be5c22c9f3c9> in <module>()
----> 1 html = template.render(**info)

/usr/lib/python2.7/site-packages/jinja2/environment.pyc in render(self, *args, **kwargs)
    967         except Exception:
    968             exc_info = sys.exc_info()
--> 969         return self.environment.handle_exception(exc_info, True)
    970 
    971     def stream(self, *args, **kwargs):

/usr/lib/python2.7/site-packages/jinja2/environment.pyc in handle_exception(self, exc_info, rendered, source_hint)
    740             self.exception_handler(traceback)
    741         exc_type, exc_value, tb = traceback.standard_exc_info
--> 742         reraise(exc_type, exc_value, tb)
    743 
    744     def join_path(self, template, parent):

<template> in top-level template code()

/usr/lib/python2.7/site-packages/jinja2/environment.pyc in getitem(self, obj, argument)
    376         """Get an item or attribute of an object but prefer the item."""
    377         try:
--> 378             return obj[argument]
    379         except (TypeError, LookupError):
    380             if isinstance(argument, string_types):

UndefinedError: 'info' is undefined

這是純Python(沒有Django,沒有Flask)。 你能告訴我哪里做錯了嗎?

您正在將info字典的傳遞給模板。 名稱info本身不適用於模板。

只需在模板中使用{{ username }}{{ netlink }}等。

或者,在渲染時以實際名稱傳遞info

html = template.render(info=info)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM