Add rudimentary Jinja2 template tag support

The following tags and filters are supported:

* `wagtailcore`:
  * `pageurl()`
  * `slugurl()`
  * `wagtail_version()`
  * `|pageurl`
* `wagtailimages`:
  * `image()`

Django template tags have been translated to Jinja functions, rather
than custom tags. Functions are easier to use compared to template tags,
and can be composed and combined for greater flexibility.

The template tag libraries have been grouped as Jinja Extensions, which
are loadable via the `extensions` option. An example Django Jinja2
configuration is:

```python
TEMPLATES = [
    # ...
    {
        'BACKEND': 'django.template.backends.jinja2.Jinja2',
        'APP_DIRS': True,
        'OPTIONS': {
            'extensions': [
                'wagtail.wagtailcore.templatetags.jinja2.core',
                'wagtail.wagtailimages.templatetags.jinja2.images',
            ],
        },
    },
]
```
This commit is contained in:
Tim Heap 2015-09-30 18:44:35 +10:00
parent 7de03ef8c4
commit de88f90b36
3 changed files with 64 additions and 0 deletions

View file

@ -0,0 +1,22 @@
import jinja2
from jinja2.ext import Extension
from .wagtailcore_tags import pageurl, richtext, slugurl, wagtail_version
class WagtailCoreExtension(Extension):
def __init__(self, environment):
super(WagtailCoreExtension, self).__init__(environment)
self.environment.globals.update({
'pageurl': jinja2.contextfunction(pageurl),
'slugurl': jinja2.contextfunction(slugurl),
'wagtail_version': wagtail_version,
})
self.environment.filters.update({
'richtext': richtext,
})
# Nicer import names
core = WagtailCoreExtension

View file

@ -448,6 +448,9 @@ class AbstractRendition(models.Model):
else:
return mark_safe('<img %s>' % self.attrs)
def __html__(self):
return self.img_tag()
class Meta:
abstract = True

View file

@ -0,0 +1,39 @@
from jinja2.ext import Extension
from wagtail.wagtailimages.models import SourceImageIOError
def image(image, filterspec, **attrs):
if not image:
return ''
try:
rendition = image.get_rendition(filterspec)
except SourceImageIOError:
# It's fairly routine for people to pull down remote databases to their
# local dev versions without retrieving the corresponding image files.
# In such a case, we would get a SourceImageIOError at the point where we try to
# create the resized version of a non-existent image. Since this is a
# bit catastrophic for a missing image, we'll substitute a dummy
# Rendition object so that we just output a broken link instead.
Rendition = image.renditions.model # pick up any custom Image / Rendition classes that may be in use
rendition = Rendition(image=image, width=0, height=0)
rendition.file.name = 'not-found'
if attrs:
return rendition.img_tag(attrs)
else:
return rendition
class WagtailImagesExtension(Extension):
def __init__(self, environment):
super(WagtailImagesExtension, self).__init__(environment)
self.environment.globals.update({
'image': image,
})
# Nicer import names
images = WagtailImagesExtension