实用工具

这些辅助函数和类在你向 Jinja2 环境中添加自定义过滤器或函数时很有用。

  • jinja2.environmentfilter(f)
  • Decorator for marking evironment dependent filters. The currentEnvironment is passed to the filter as first argument.
  • jinja2.contextfilter(f)
  • Decorator for marking context dependent filters. The currentContext will be passed as first argument.
  • jinja2.evalcontextfilter(f)
  • Decorator for marking eval-context dependent filters. An evalcontext object is passed as first argument. For more informationabout the eval context, see 求值上下文.

New in version 2.4.

  • jinja2.environmentfunction(f)
  • This decorator can be used to mark a function or method as environmentcallable. This decorator works exactly like the contextfunction()decorator just that the first argument is the active Environmentand not context.
  • jinja2.contextfunction(f)
  • This decorator can be used to mark a function or method context callable.A context callable is passed the active Context as first argument whencalled from the template. This is useful if a function wants to get accessto the context or functions provided on the context object. For examplea function that returns a sorted list of template variables the currenttemplate exports could look like this:
  1. @contextfunction
  2. def get_exported_names(context):
  3. return sorted(context.exported_vars)
  • jinja2.evalcontextfunction(f)
  • This decorator can be used to mark a function or method as an evalcontext callable. This is similar to the contextfunction()but instead of passing the context, an evaluation context object ispassed. For more information about the eval context, see求值上下文.

New in version 2.4.

  • jinja2.escape(s)
  • 把字符串 s 中 & 、 < 、 > 、 ' 和 " 转换为 HTML 安全的序列。如果你需要在 HTML 中显示可能包含这些字符的文本,可以使用它。这个函数不会转义对象。这个函数不会转义含有 HTML 表达式比如已转义数据的对象。

返回值是一个 Markup 字符串。

  • jinja2.clear_caches()
  • Jinja2 keeps internal caches for environments and lexers. These areused so that Jinja2 doesn’t have to recreate environments and lexers allthe time. Normally you don’t have to care about that but if you aremessuring memory consumption you may want to clean the caches.
  • jinja2.isundefined(_obj)
  • Check if the object passed is undefined. This does nothing more thanperforming an instance check against Undefined but looks nicer.This can be used for custom filters or tests that want to react toundefined variables. For example a custom default filter can look likethis:
  1. def default(var, default=''):
  2. if is_undefined(var):
  3. return default
  4. return var
  • class _jinja2.Markup([_string])
  • Marks a string as being safe for inclusion in HTML/XML output withoutneeding to be escaped. This implements the html interface a coupleof frameworks and web applications use. Markup is a directsubclass of unicode and provides all the methods of unicode just thatit escapes arguments passed and always returns Markup.

The escape function returns markup objects so that double escaping can’thappen.

The constructor of the Markup class can be used for threedifferent things: When passed an unicode object it’s assumed to be safe,when passed an object with an HTML representation (has an htmlmethod) that representation is used, otherwise the object passed isconverted into a unicode string and then assumed to be safe:

  1. >>> Markup("Hello <em>World</em>!")
  2. Markup(u'Hello <em>World</em>!')
  3. >>> class Foo(object):
  4. ... def __html__(self):
  5. ... return '<a href="#">foo</a>'
  6. ...
  7. >>> Markup(Foo())
  8. Markup(u'<a href="#">foo</a>')

If you want object passed being always treated as unsafe you can use theescape() classmethod to create a Markup object:

  1. >>> Markup.escape("Hello <em>World</em>!")
  2. Markup(u'Hello &lt;em&gt;World&lt;/em&gt;!')

Operations on a markup string are markup aware which means that allarguments are passed through the escape() function:

  1. >>> em = Markup("<em>%s</em>")
  2. >>> em % "foo & bar"
  3. Markup(u'<em>foo &amp; bar</em>')
  4. >>> strong = Markup("<strong>%(text)s</strong>")
  5. >>> strong % {'text': '<blink>hacker here</blink>'}
  6. Markup(u'<strong>&lt;blink&gt;hacker here&lt;/blink&gt;</strong>')
  7. >>> Markup("<em>Hello</em> ") + "<foo>"
  8. Markup(u'<em>Hello</em> &lt;foo&gt;')
  • classmethod _escape(_s)
  • Escape the string. Works like escape() with the differencethat for subclasses of Markup this function would return thecorrect subclass.

  • striptags()

  • Unescape markup into an text_type string and strip all tags. Thisalso resolves known HTML4 and XHTML entities. Whitespace isnormalized to one:
  1. >>> Markup("Main &raquo; <em>About</em>").striptags()
  2. u'Main \xbb About'
  • unescape()
  • Unescape markup again into an text_type string. This also resolvesknown HTML4 and XHTML entities:
  1. >>> Markup("Main &raquo; <em>About</em>").unescape()
  2. u'Main \xbb <em>About</em>'

Note

Jinja2 的 Markup 类至少与 Pylons 和 Genshi 兼容。预计不久更多模板引擎和框架会采用 html 的概念。