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
Provenance
- Commit
58f351d- Tree
d78575a- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
9ddd0b8
4 files changed+103 added−32 removed
modified:docs/api.rst+32 added-11 removed
87 unmodified lines88 89 For more details about unicode in Python have a look at the excellent90 `Unicode documentation`_.91 92+Another important thing is how Jinja2 is handling string literals in93+templates. A naive implementation would be using unicode strings for94+all string literals but it turned out in the past that this is problematic95+as some libraries are typechecking against `str` explicitly. For example96+`datetime.strftime` does not accept unicode arguments. To not break it97+completely Jinja2 is returning `str` for strings that fit into ASCII and98+for everything else `unicode`:99 100+>>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module101+>>> m.a102+'foo'103+>>> m.b104+u'f\xf6\xf6'105+106+107 .. _Unicode documentation: http://docs.python.org/dev/howto/unicode.html108 109 High Level API110 --------------42 unmodified lines153 For valid object names have a look at :ref:`identifier-naming`.154 155 .. automethod:: overlay([options])156 143- .. method:: undefined([hint,] [obj,] name[, exc])157+ .. method:: undefined([hint, obj, name, exc])158 159 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 provided136 unmodified lines298 def __float__(self):299 return 0.0300 301 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::307 308 class NonIterableUndefined(Undefined):309 __iter__ = Undefined._fail_with_undefined_error310 112 unmodified lines423 .. autofunction:: jinja2.utils.clear_caches424 425 .. autofunction:: jinja2.utils.is_undefined426 413-.. autoclass:: jinja2.utils.Markup427+.. autoclass:: jinja2.utils.Markup([string])428+ :members: escape, unescape, striptags429 430+.. admonition:: Note431 432+ 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.435+436+437 Exceptions438 ----------439 440 .. autoexception:: jinja2.exceptions.TemplateError175 unmodified lines616 available, otherwise `True`.617 618 .. admonition:: Note619 599- 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 lines22 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 pieces29 30 243 unmodified linesmodified:jinja2/utils.py+59 added-9 removed
68 unmodified lines69 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::72 73- @contextcallable73+ @contextfunction74 def get_exported_names(context):75 return sorted(context.exported_vars)76 """77 f.contextfunction = True169 unmodified lines247 return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result))248 249 250 class 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`.256 257 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`.260+261+ 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:266+267+ >>> 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>')275+276+ If you want object passed being always treated as unsafe you can use the277+ :meth:`escape` classmethod to create a :class:`Markup` object:278+279+ >>> Markup.escape("Hello <em>World</em>!")280+ Markup(u'Hello <em>World</em>!')281+282+ Operations on a markup string are markup aware which means that all283+ arguments are passed through the :func:`escape` function:284+285+ >>> em = Markup("<em>%s</em>")286+ >>> em % "foo & bar"287+ Markup(u'<em>foo & bar</em>')288+ >>> strong = Markup("<strong>%(text)s</strong>")289+ >>> strong % {'text': '<blink>hacker here</blink>'}290+ Markup(u'<strong><blink>hacker here</blink></strong>')291+ >>> Markup("<em>Hello</em> ") + "<foo>"292+ Markup(u'<em>Hello</em> <foo>')293 """294 __slots__ = ()295 296 def __new__(cls, base=u''):49 unmodified lines346 return map(self.__class__, unicode.splitlines(self, *args, **kwargs))347 splitlines.__doc__ = unicode.splitlines.__doc__348 349 def unescape(self):315- """Unescape markup."""350+ r"""Unescape markup again into an unicode string. This also resolves351+ known HTML4 and XHTML entities:352+353+ >>> Markup("Main » <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 lines367 return u''368 return _entity_re.sub(handle_match, unicode(self))369 370 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:374+375+ >>> Markup("Main » <em>About</em>").striptags()376+ u'Main \xbb About'377+ """378 stripped = u' '.join(_striptags_re.sub('', self).split())379 return Markup(stripped).unescape()380 381 @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 rv49 unmodified lines440 441 442 class 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.444 445+ # 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.448+449 def __init__(self, capacity):450 self.capacity = capacity451 self._mapping = {}452 self._queue = deque()205 unmodified linesmodified:setup.py+11 added-11 removed
47 unmodified lines48 from distutils.command.build_ext import build_ext49 from distutils.errors import CCompilerError, DistutilsPlatformError50 51 52-def 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 fn52+data_files = []53+documentation_path = 'docs/_build/html'54+if 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))62 63 64 def get_terminal_width():65 """Return the current terminal dimensions."""27 unmodified lines93 print '*' * width94 print """WARNING:95 An optional C extension could not be compiled, speedups will not be96 available."""94- print '*' * width97 98 99 setup(100 name='Jinja2',19 unmodified lines120 '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