Skip to content
Myr

data files are optional now

Before adoption: this commit came in with the history the project adopted, so no landing records it.

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent 9ddd0b8 · Browse files · 4 files+103 added−32 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+103 added−32 removed

  • other:+103 added−32 removed

4 files+103 added−32 removed

modified:docs/api.rst+32 added-11 removed
87 unmodified lines
8889For more details about unicode in Python have a look at the excellent90`Unicode documentation`_.9192Another important thing is how Jinja2 is handling string literals in93templates. A naive implementation would be using unicode strings for94all string literals but it turned out in the past that this is problematic95as some libraries are typechecking against `str` explicitly. For example96`datetime.strftime` does not accept unicode arguments. To not break it97completely Jinja2 is returning `str` for strings that fit into ASCII and98for everything else `unicode`:99100>>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module101>>> m.a102'foo'103>>> m.b104u'f\xf6\xf6'105106107.. _Unicode documentation: http://docs.python.org/dev/howto/unicode.html108109High Level API110--------------
42 unmodified lines
153 For valid object names have a look at :ref:`identifier-naming`.154155 .. automethod:: overlay([options])156143 .. method:: undefined([hint,] [obj,] name[, exc])157 .. method:: undefined([hint, obj, name, exc])158159 Creates a new :class:`Undefined` object for `name`. This is useful160 for filters or functions that may return undefined objects for161 some operations. All parameters except of `hint` should be provided
136 unmodified lines
298 def __float__(self):299 return 0.0300301 To disallow a method, just override it and raise288 :attr:`_undefined_exception`. Because this is a very common idom in289 undefined objects there is the helper method290 :meth:`_fail_with_undefined_error`. That does that automatically. Here291 a class that works like the regular :class:`UndefinedError` but chokes292 on iteration::302 :attr:`~Undefined._undefined_exception`. Because this is a very common303 idom in undefined objects there is the helper method304 :meth:`~Undefined._fail_with_undefined_error` that does the error raising305 automatically. Here a class that works like the regular :class:`Undefined`306 but chokes on iteration::307308 class NonIterableUndefined(Undefined):309 __iter__ = Undefined._fail_with_undefined_error310
112 unmodified lines
423.. autofunction:: jinja2.utils.clear_caches424425.. autofunction:: jinja2.utils.is_undefined426413.. autoclass:: jinja2.utils.Markup427.. autoclass:: jinja2.utils.Markup([string])428 :members: escape, unescape, striptags429430.. admonition:: Note431432 The Jinja2 :class:`Markup` class is compatible with at least Pylons and433 Genshi. It's expected that more template engines and framework will pick434 up the `__html__` concept soon.435436437Exceptions438----------439440.. autoexception:: jinja2.exceptions.TemplateError
175 unmodified lines
616 available, otherwise `True`.617618.. admonition:: Note619599 The low-level API is fragile. Future Jinja2 versions will not change it600 in a backwards incompatible way but modifications in the Jinja core may601 shine through. For example if Jinja2 introduces a new AST node in later602 versions that may be returned by :meth:`~Environment.parse`.620 The low-level API is fragile. Future Jinja2 versions will try not to621 change it in a backwards incompatible way but modifications in the Jinja2622 core may shine through. For example if Jinja2 introduces a new AST node623 in later versions that may be returned by :meth:`~Environment.parse`.
modified:jinja2/loaders.py+1 added-1 removed
21 unmodified lines
22 if path.sep in piece \23 or (path.altsep and path.altsep in piece) or \24 piece == path.pardir:25 raise TemplateNotFound(template)26 elif piece != '.':26 elif piece and piece != '.':27 pieces.append(piece)28 return pieces2930
243 unmodified lines
modified:jinja2/utils.py+59 added-9 removed
68 unmodified lines
69 to the context or functions provided on the context object. For example70 a function that returns a sorted list of template variables the current71 template exports could look like this::7273 @contextcallable73 @contextfunction74 def get_exported_names(context):75 return sorted(context.exported_vars)76 """77 f.contextfunction = True
169 unmodified lines
247 return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result))248249250class Markup(unicode):251 """Marks a string as being safe for inclusion in HTML/XML output without251 r"""Marks a string as being safe for inclusion in HTML/XML output without252 needing to be escaped. This implements the `__html__` interface a couple253 of frameworks and web applications use.253 of frameworks and web applications use. :class:`Markup` is a direct254 subclass of `unicode` and provides all the methods of `unicode` just that255 it escapes arguments passed and always returns `Markup`.256257 The `escape` function returns markup objects so that double escaping can't258 happen. If you want to use autoescaping in Jinja just set the finalizer259 of the environment to `escape`.260261 The constructor of the :class:`Markup` class can be used for three262 different things: When passed an unicode object it's assumed to be safe,263 when passed an object with an HTML representation (has an `__html__`264 method) that representation is used, otherwise the object passed is265 converted into a unicode string and then assumed to be safe:266267 >>> Markup("Hello <em>World</em>!")268 Markup(u'Hello <em>World</em>!')269 >>> class Foo(object):270 ... def __html__(self):271 ... return '<a href="#">foo</a>'272 ... 273 >>> Markup(Foo())274 Markup(u'<a href="#">foo</a>')275276 If you want object passed being always treated as unsafe you can use the277 :meth:`escape` classmethod to create a :class:`Markup` object:278279 >>> Markup.escape("Hello <em>World</em>!")280 Markup(u'Hello &lt;em&gt;World&lt;/em&gt;!')281282 Operations on a markup string are markup aware which means that all283 arguments are passed through the :func:`escape` function:284285 >>> em = Markup("<em>%s</em>")286 >>> em % "foo & bar"287 Markup(u'<em>foo &amp; bar</em>')288 >>> strong = Markup("<strong>%(text)s</strong>")289 >>> strong % {'text': '<blink>hacker here</blink>'}290 Markup(u'<strong>&lt;blink&gt;hacker here&lt;/blink&gt;</strong>')291 >>> Markup("<em>Hello</em> ") + "<foo>"292 Markup(u'<em>Hello</em> &lt;foo&gt;')293 """294 __slots__ = ()295296 def __new__(cls, base=u''):
49 unmodified lines
346 return map(self.__class__, unicode.splitlines(self, *args, **kwargs))347 splitlines.__doc__ = unicode.splitlines.__doc__348349 def unescape(self):315 """Unescape markup."""350 r"""Unescape markup again into an unicode string. This also resolves351 known HTML4 and XHTML entities:352353 >>> Markup("Main &raquo; <em>About</em>").unescape()354 u'Main \xbb <em>About</em>'355 """356 def handle_match(m):357 name = m.group(1)358 if name in _entities:359 return unichr(_entities[name])
7 unmodified lines
367 return u''368 return _entity_re.sub(handle_match, unicode(self))369370 def striptags(self):331 """Strip tags and resolve enities."""371 r"""Unescape markup into an unicode string and strip all tags. This372 also resolves known HTML4 and XHTML entities. Whitespace is373 normalized to one:374375 >>> Markup("Main &raquo; <em>About</em>").striptags()376 u'Main \xbb About'377 """378 stripped = u' '.join(_striptags_re.sub('', self).split())379 return Markup(stripped).unescape()380381 @classmethod382 def escape(cls, s):337 """Escape the string. Works like :func:`escape`."""383 """Escape the string. Works like :func:`escape` with the difference384 that for subclasses of :class:`Markup` this function would return the385 correct subclass.386 """387 rv = escape(s)388 if rv.__class__ is not cls:389 return cls(rv)390 return rv
49 unmodified lines
440441442class LRUCache(object):443 """A simple LRU Cache implementation."""395 # this is fast for small capacities (something around 200) but doesn't396 # scale. But as long as it's only used for the database connections in397 # a non request fallback it's fine.444445 # this is fast for small capacities (something below 1000) but doesn't446 # scale. But as long as it's only used as storage for templates this447 # won't do any harm.448449 def __init__(self, capacity):450 self.capacity = capacity451 self._mapping = {}452 self._queue = deque()
205 unmodified lines
modified:setup.py+11 added-11 removed
47 unmodified lines
48from distutils.command.build_ext import build_ext49from distutils.errors import CCompilerError, DistutilsPlatformError505152def list_files(path):53 for fn in os.listdir(path):54 if fn.startswith('.'):55 continue56 fn = os.path.join(path, fn)57 if os.path.isfile(fn):58 yield fn52data_files = []53documentation_path = 'docs/_build/html'54if os.path.exists(documentation_path):55 documentation_files = []56 for fn in os.listdir(documentation_path):57 if not fn.startswith('.'):58 fn = os.path.join(documentation_path, fn)59 if os.path.isfile(fn):60 documentation_files.append(fn)61 data_files.append(('docs', documentation_files))626364def get_terminal_width():65 """Return the current terminal dimensions."""
27 unmodified lines
93 print '*' * width94 print """WARNING:95An optional C extension could not be compiled, speedups will not be96available."""94 print '*' * width979899setup(100 name='Jinja2',
19 unmodified lines
120 'Topic :: Software Development :: Libraries :: Python Modules',121 'Topic :: Text Processing :: Markup :: HTML'122 ],123 packages=['jinja2'],122 data_files=[123 ('docs', list(list_files('docs/_build/html')))124 ],124 data_files=data_files,125 features={126 'speedups': Feature("optional C speed-enhancements",127 standard=True,128 ext_modules=[
10 unmodified lines