<s> from __future__ import absolute_import , unicode_literals <EOL> import re <EOL> from django import template <EOL> from django . utils . functional import cached_property <EOL> from wagtail . wagtailimages . models import Filter <EOL> from wagtail . wagtailimages . shortcuts import get_rendition_or_not_found <EOL> register = template . Library ( ) <EOL> allowed_filter_pattern = re . compile ( "<STR_LIT>" ) <EOL> @ register . tag ( name = "<STR_LIT:image>" ) <EOL> def image ( parser , token ) : <EOL> bits = token . split_contents ( ) [ <NUM_LIT:1> : ] <EOL> image_expr = parser . compile_filter ( bits [ <NUM_LIT:0> ] ) <EOL> bits = bits [ <NUM_LIT:1> : ] <EOL> filter_specs = [ ] <EOL> attrs = { } <EOL> output_var_name = None <EOL> as_context = False <EOL> is_valid = True <EOL> for bit in bits : <EOL> if bit == '<STR_LIT>' : <EOL> as_context = True <EOL> elif as_context : <EOL> if output_var_name is None : <EOL> output_var_name = bit <EOL> else : <EOL> is_valid = False <EOL> else : <EOL> try : <EOL> name , value = bit . split ( '<STR_LIT:=>' ) <EOL> attrs [ name ] = parser . compile_filter ( value ) <EOL> except ValueError : <EOL> if allowed_filter_pattern . match ( bit ) : <EOL> filter_specs . append ( bit ) <EOL> else : <EOL> raise template . TemplateSyntaxError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" . format ( bit ) <EOL> ) <EOL> if as_context and output_var_name is None : <EOL> is_valid = False <EOL> if output_var_name and attrs : <EOL> is_valid = False <EOL> if is_valid : <EOL> return ImageNode ( image_expr , '<STR_LIT:|>' . join ( filter_specs ) , attrs = attrs , output_var_name = output_var_name ) <EOL> else : <EOL> raise template . TemplateSyntaxError ( <EOL> "<STR_LIT>" <EOL> "<STR_LIT>" <EOL> ) <EOL> class ImageNode ( template . Node ) : <EOL> def __init__ ( self , image_expr , filter_spec , output_var_name = None , attrs = { } ) : <EOL> self . image_expr = image_expr <EOL> self . output_var_name = output_var_name <EOL> self . attrs = attrs <EOL> self . filter_spec = filter_spec <EOL> @ cached_property <EOL> def filter ( self ) : <EOL> _filter , _ = Filter . objects . get_or_create ( spec = self . filter_spec ) <EOL> return _filter <EOL> def render ( self , context ) : <EOL> try : <EOL> image = self . image_expr . resolve ( context ) <EOL> except template . VariableDoesNotExist : <EOL> return '<STR_LIT>' <EOL> if not image : <EOL> return '<STR_LIT>' <EOL> rendition = get_rendition_or_not_found ( image , self . filter ) <EOL> if self . output_var_name : <EOL> context [ self . output_var_name ] = rendition <EOL> return '<STR_LIT>' <EOL> else : <EOL> resolved_attrs = { } <EOL> for key in self . attrs : <EOL> resolved_attrs [ key ] = self . attrs [ key ] . resolve ( context ) <EOL> return rendition . img_tag ( resolved_attrs ) </s>
