def __init__(self, parser, token): # noqa D102 bits = token.split_contents() if len(bits) > 5: raise TemplateSyntaxError( "%r accepts at most 4 arguments (part_id, section," " asvar, varname), got: {}".format(bits[0], ','.join(bits[1:])) ) self.part_id = Variable(bits[1]) self.section = bits[2] if len(bits) >= 3 else None self.varname = None if len(bits) > 3: if bits[3] != 'asvar': raise TemplateSyntaxError( 'Forth argument should be asvar," " got {}'.format(bits[3]) ) if len(bits) < 4: raise TemplateSyntaxError('Variable name not provided') else: self.varname = Variable(bits[4]) self.nodelist = parser.parse(('end{}'.format(bits[0]),)) parser.delete_first_token()
def __init__(self, parser, token): # noqa D102 bits = token.split_contents() if len(bits) < 3: raise TemplateSyntaxError( "%r accepts at least 2 arguments (bound_field," " 'groupname'), got: {}".format(bits[0], ','.join(bits[1:])) ) if len(bits) > 5: raise TemplateSyntaxError( "%r accepts at mast 4 arguments (bound_field, 'groupname'" " default attrs_dict ), got: {}".format( bits[0], ','.join(bits[1:])) ) if len(bits) > 3 and bits[3] != 'default': raise TemplateSyntaxError( "%r 3d argument should be 'default' (bound_field, 'groupname'" " default attrs_dict ), got: {}".format( bits[0], ','.join(bits[1:])) ) self.field = Variable(bits[1]) self.group = Variable(bits[2]) self.widget_attrs = Variable(bits[4]) if len(bits) >= 5 else None self.nodelist = parser.parse(('end{}'.format(bits[0]))) parser.delete_first_token()
def __init__(self, parser, token): # noqa D102 bits = token.split_contents() if len(bits) < 4: raise TemplateSyntaxError( "{} accepts at least 3 arguments (bound_field, 'groupname'" " 'attr_name'), got: {}".format(bits[0], ','.join(bits[1:])) ) if len(bits) > 5: raise TemplateSyntaxError( "{} accepts at mast 4 arguments (bound_field, 'groupname'" " 'attr_name' action ), got: {}".format( bits[0], ','.join(bits[1:])) ) if len(bits) >= 5 and bits[4] not in ['append', 'override']: raise TemplateSyntaxError( "{} unknown action {} should be 'append'" " of 'override'".format(bits[0], ','.join(bits[4])) ) self.field = Variable(bits[1]) self.group = Variable(bits[2]) self.attr = bits[3] self.action = bits[4] if len(bits) >= 5 else 'override' self.nodelist = parser.parse(('end{}'.format(bits[0]))) parser.delete_first_token()
def render(self, context): try: actual_object = Variable(self.object_to_get_absolute_url).resolve(context) absolute_url = actual_object.get_absolute_url() return self.get_admin_absolute_url(absolute_url) except VariableDoesNotExist: return ''
class FormPartNode(Node): """ Named piece of HTML layout. """ def __init__(self, parser, token): bits = token.split_contents() if len(bits) > 5: raise TemplateSyntaxError( "%r accepts at most 4 arguments (part_id, section, asvar, varname), got: {}" % (bits[0], ','.join(bits[1:]))) self.part_id = Variable(bits[1]) self.section = bits[2] if len(bits) >= 3 else None self.varname = None if len(bits) > 3: if bits[3] != 'asvar': raise TemplateSyntaxError('Forth argument should be asvar, got {}', format(bits[3])) if len(bits) < 4: raise TemplateSyntaxError('Variable name not provided') else: self.varname = Variable(bits[4]) self.nodelist = parser.parse(('end{}'.format(bits[0]),)) parser.delete_first_token() def resolve_part(self, context): part = self.part_id.resolve(context) if isinstance(part, BoundField): part = part.field return part def render(self, context): part = self.resolve_part(context) parts = context['form_parts'] if self.section in parts[part]: # already rendered if self.varname is not None: context[self.varname.resolve(context)] = parts[part][self.section] return "" else: return parts[part][self.section] # child parts children = (node for node in self.nodelist if isinstance(node, FormPartNode)) _render_parts(context, children) # render own content value = self.nodelist.render(context).strip() if self.varname is not None: context[self.varname.resolve(context)] = value return '' else: if not value: return '' return value
def render(self, context): dict = Variable(self.dict).resolve(context) key = context.get(self.key, self.key) default = context.get(self.default, self.default) if dict: context[self.context_key] = dict.get(key, default) else: context[self.context_key] = default return ''
class WidgetAttrNode(Node): """ {% attr form.email 'widget' 'data-validate' %}email{% endattr %} {% attr form.email 'widget' 'class' append %}green{% endattr %} {% attr form.email 'widget' 'required' %}True{% endattr %} """ def __init__(self, parser, token): bits = token.split_contents() if len(bits) < 4: raise TemplateSyntaxError( "{} accepts at least 3 arguments (bound_field, 'groupname' 'attr_name'), got: {}".format( (bits[0], ','.join(bits[1:])))) if len(bits) > 5: raise TemplateSyntaxError( "{} accepts at mast 4 arguments (bound_field, 'groupname' 'attr_name' action ), got: {}".format( (bits[0], ','.join(bits[1:])))) if len(bits) >= 5 and bits[4] not in ['append', 'override']: raise TemplateSyntaxError( "{} unknown action {} should be 'append' of 'override'".format( (bits[0], ','.join(bits[4])))) self.field = Variable(bits[1]) self.group = Variable(bits[2]) self.attr = bits[3] self.action = bits[4] if len(bits) >= 5 else 'override' self.nodelist = parser.parse(('end{}'.format(bits[0]),)) parser.delete_first_token() def resolve_field(self, context): field = self.field.resolve(context) if isinstance(field, BoundField): field = field.field return field def render(self, context): field = self.resolve_field(context) group = self.group.resolve(context) form_widget_attrs = context['form_widget_attrs'] value = self.nodelist.render(context) if group not in form_widget_attrs[field]: form_widget_attrs[field][group] = {} attrs = form_widget_attrs[field][group] if self.attr not in attrs or self.action == 'override': attrs[self.attr] = (value, self.action) else: old_value, old_action = attrs[self.attr] if old_action != 'override': attrs[self.attr] = ('{} {}'.format(old_value, value), self.action)
def render(self, context): request = context.get('request') if request: form_object = Variable(self.form_object_variable).resolve(context) if request.method == "GET": form = form_object.empty_form() elif request.method == "POST": form_object.process_form(request) form = form_object.bound_form else: form = None context[self.varname] = form return ''
def __init__(self, parser, token): bits = token.split_contents() if len(bits) == 0: raise TemplateSyntaxError( "%r received invalid args, expected one element for render. Got: %r" % (bits[0], bits[1:])) remaining_bits = bits[2:] self.kwargs = token_kwargs(remaining_bits, parser) if remaining_bits: raise TemplateSyntaxError("%r received an invalid token: %r" % (bits[0], remaining_bits[0])) for key in self.kwargs: if key not in ('template', 'widget'): raise TemplateSyntaxError("%r received an invalid key: %r" % (bits[0], key)) self.kwargs[key] = self.kwargs[key] self.nodelist = parser.parse(('end{}'.format(bits[0]),)) parser.delete_first_token() self.element = Variable(bits[1])
class _ABTestNode(Node): def __init__(self, ab_test_name, variant_a_content, variant_b_content): self.ab_test_name = Variable(ab_test_name) self.variant_a_content = variant_a_content self.variant_b_content = variant_b_content def render(self, context): ab_test_name = self.ab_test_name.resolve(context) ab_test = ABTest.objects.get_or_create(name=ab_test_name)[0] block_context = context.copy() block_context["ab_test"] = ab_test if self._is_variant_a_applicable(context["request"]): block_context["ab_test_variant"] = VARIANT_A content = self.variant_a_content.render(block_context) ab_test.times_a_presented += 1 else: block_context["ab_test_variant"] = VARIANT_B content = self.variant_b_content.render(block_context) ab_test.times_b_presented += 1 ab_test.save() return content @staticmethod def _is_variant_a_applicable(request): raise NotImplementedError("Determine whether A or B is applicable!")
class IncludeHandlebarsNode(Node): def __init__(self, name): self.name = Variable(name) def render(self, context): name = self.name.resolve(context) template = get_template(name) return template.render(context)
def render(self, context): provider = Variable(self.provider).resolve(context) media = forms.Media(css = widgets.CategorySelectWidget.Media.css, \ js = widgets.CategorySelectWidget.Media.js) context[self.media_key] = media attrs = { 'id': 'category-tree-{0}'.format(slugify(provider)), 'class' : 'category-tree', } for key, value in self.attrs.items(): if self.attrs[key] == True: attrs[key] = True else: attrs[key] = Variable(value).resolve(context) root = None if self.root: root = Variable(self.root).resolve(context) if self.template_name is None: template_name = 'category/render-tree.html' else: template_name = Variable(self.template_name).resolve(context) provider = cache.get_object(provider) if root: if isinstance(root, Category): if root.is_root: root = root else: root = root.root else: root = get_root(name = root) else: root = provider.get_root_category() cache.add_object(provider, root.pk) kw = { 'template_name':template_name, 'context': context, 'collapse': self.collapse, 'attrs' : attrs, } return do_render_tree(provider, root, **kw)
class FormRenderNode(Node): def __init__(self, parser, token): bits = token.split_contents() if len(bits) == 0: raise TemplateSyntaxError( "%r received invalid args, expected one element for render. Got: %r" % (bits[0], bits[1:])) remaining_bits = bits[2:] self.kwargs = token_kwargs(remaining_bits, parser) if remaining_bits: raise TemplateSyntaxError("%r received an invalid token: %r" % (bits[0], remaining_bits[0])) for key in self.kwargs: if key not in ('template', 'widget'): raise TemplateSyntaxError("%r received an invalid key: %r" % (bits[0], key)) self.kwargs[key] = self.kwargs[key] self.nodelist = parser.parse(('end{}'.format(bits[0]),)) parser.delete_first_token() self.element = Variable(bits[1]) def render(self, context): element = self.element.resolve(context) options = {} for key, value in self.kwargs.items(): options[key] = value.resolve(context) # render inner parts children = (node for node in self.nodelist if isinstance(node, FormPartNode)) _render_parts(context, children) attrs = (node for node in self.nodelist if isinstance(node, WidgetAttrNode)) for attr in attrs: attr.render(context) # render element if isinstance(element, BoundField): return Field(element.name).render(context, **options) elif hasattr(element, 'render'): with context.push(parent=element): return element.render(context, **options) else: raise TemplateSyntaxError("form_render can't render %r" % (element, ))
def __init__(self, parser, token): bits = token.split_contents() if len(bits) > 3: raise TemplateSyntaxError( "%r accepts at most 2 arguments (part_id, section), got: {}" % (bits[0], bits[1:])) self.part_id = Variable(bits[1]) self.section = bits[2] if len(bits) == 3 else None self.nodelist = parser.parse(('end{}'.format(bits[0]),)) parser.delete_first_token()
class IncludeNode(Node): def __init__(self, template_name): self.template_name = Variable(template_name) def render(self, context): try: template_name = self.template_name.resolve(context) t = get_template(template_name) return t.render(context) except TemplateSyntaxError, e: if settings.TEMPLATE_DEBUG: raise return '' except:
class FormPartNode(Node): def __init__(self, parser, token): bits = token.split_contents() if len(bits) > 3: raise TemplateSyntaxError( "%r accepts at most 2 arguments (part_id, section), got: {}" % (bits[0], bits[1:])) self.part_id = Variable(bits[1]) self.section = bits[2] if len(bits) == 3 else None self.nodelist = parser.parse(('end{}'.format(bits[0]),)) parser.delete_first_token() def resolve_part(self, context): part = self.part_id.resolve(context) if isinstance(part, BoundField): part = part.field return part def render(self, context): part = self.resolve_part(context) parts = context['form_parts'] if self.section in parts[part]: # already rendered return parts[part][self.section] # child parts children = (node for node in self.nodelist if isinstance(node, FormPartNode)) _render_parts(context, children) # render own content value = self.nodelist.render(context) if not value.strip(): return '' return value
def get_date(x): return Variable(arg).resolve(x) or datetime.date( datetime.MINYEAR, 1, 1)
def __init__(self, settingsvar, asvar): self.arg = Variable(settingsvar) self.asvar = asvar
class FormPartNode(Node): """ Named piece of HTML layout. """ def __init__(self, parser, token): bits = token.split_contents() if len(bits) > 5: raise TemplateSyntaxError( "%r accepts at most 4 arguments (part_id, section, asvar, varname), got: {}" % (bits[0], ','.join(bits[1:]))) self.part_id = Variable(bits[1]) self.section = bits[2] if len(bits) >= 3 else None self.varname = None if len(bits) > 3: if bits[3] != 'asvar': raise TemplateSyntaxError( 'Forth argument should be asvar, got {}', format(bits[3])) if len(bits) < 4: raise TemplateSyntaxError('Variable name not provided') else: self.varname = Variable(bits[4]) self.nodelist = parser.parse(('end{}'.format(bits[0]), )) parser.delete_first_token() def resolve_part(self, context): part = self.part_id.resolve(context) if isinstance(part, BoundField): part = part.field return part def render(self, context): part = self.resolve_part(context) parts = context['form_parts'] if self.section in parts[part]: # already rendered if self.varname is not None: context[self.varname.resolve(context)] = parts[part][ self.section] return "" else: return parts[part][self.section] # child parts children = (node for node in self.nodelist if isinstance(node, FormPartNode)) _render_parts(context, children) # render own content value = self.nodelist.render(context).strip() if self.varname is not None: context[self.varname.resolve(context)] = value return '' else: if not value: return '' return value
def test_integer_literals(self): self.assertEqual( Variable('999999999999999999999999999').literal, 999999999999999999999999999)
class FormRenderNode(Node): """Sugar for element in template rendering.""" def __init__(self, parser, token): # noqa D102 bits = token.split_contents() if len(bits) == 0: raise TemplateSyntaxError( "%r received invalid args, expected one element for render." " Got: %r".format(bits[0], bits[1:]) ) remaining_bits = bits[2:] self.kwargs = token_kwargs(remaining_bits, parser) if remaining_bits: raise TemplateSyntaxError("%r received an invalid token: %r" % (bits[0], remaining_bits[0])) for key in self.kwargs: if key not in ('template', 'widget'): raise TemplateSyntaxError("%r received an invalid key: %r" % (bits[0], key)) self.kwargs[key] = self.kwargs[key] self.nodelist = parser.parse(('end{}'.format(bits[0]),)) parser.delete_first_token() self.element = Variable(bits[1]) def render(self, context): # noqa D102 element = self.element.resolve(context) options = {} for key, value in self.kwargs.items(): options[key] = value.resolve(context) # render inner parts children = ( node for node in self.nodelist if isinstance(node, FormPartNode) ) _render_parts(context, children) attrs = ( node for node in self.nodelist if isinstance(node, WidgetAttrNode) ) for attr in attrs: attr.render(context) # render element if isinstance(element, BoundField): return Field(element.name).render(context, **options) elif hasattr(element, 'render'): with context.push(parent=element): return element.render(context, **options) else: raise TemplateSyntaxError( "form_render can't render %r".format(element) )
def __init__(self, num, context_name): self.num, self.context_name = Variable(num), context_name
class RangeNode(Node): def __init__(self, num, context_name): self.num, self.context_name = Variable(num), context_name def render(self, context): context[self.context_name] = range(int(self.num.resolve(context))) return ""
def __init__(self, template_name): self.template_name = Variable(template_name)
def __init__(self, name): self.name = Variable(name)
def dictsortreversed(value, arg): """ Takes a list of dicts, returns that list sorted in reverse order by the property given in the argument. """ return sorted(value, key=Variable(arg).resolve, reverse=True)
class WidgetAttrNode(Node): """The tag allows to add or override specific attribute in the rendered HTML. The first argumnent is the attribute group name, second is the attribute name. The third optional flag shows to override (by default) or `append` the value. Usage:: {% attr form.email 'widget' 'data-validate' %}email{% endattr %} {% attr form.email 'widget' 'class' append %}green{% endattr %} {% attr form.email 'widget' 'required' %}True{% endattr %} """ def __init__(self, parser, token): # noqa D102 bits = token.split_contents() if len(bits) < 4: raise TemplateSyntaxError( "{} accepts at least 3 arguments (bound_field, 'groupname'" " 'attr_name'), got: {}".format(bits[0], ','.join(bits[1:]))) if len(bits) > 5: raise TemplateSyntaxError( "{} accepts at mast 4 arguments (bound_field, 'groupname'" " 'attr_name' action ), got: {}".format( bits[0], ','.join(bits[1:]))) if len(bits) >= 5 and bits[4] not in ['append', 'override']: raise TemplateSyntaxError( "{} unknown action {} should be 'append'" " of 'override'".format(bits[0], ','.join(bits[4]))) self.field = Variable(bits[1]) self.group = Variable(bits[2]) self.attr = bits[3] self.action = bits[4] if len(bits) >= 5 else 'override' self.nodelist = parser.parse(('end{}'.format(bits[0]))) parser.delete_first_token() def resolve_field(self, context): """Resolve field reference form context.""" field = self.field.resolve(context) if isinstance(field, BoundField): field = field.field return field def render(self, context): # noqa D102 field = self.resolve_field(context) group = self.group.resolve(context) form_widget_attrs = context['form_widget_attrs'] value = self.nodelist.render(context) if group not in form_widget_attrs[field]: form_widget_attrs[field][group] = {} attrs = form_widget_attrs[field][group] if self.attr not in attrs or self.action == 'override': attrs[self.attr] = (value, self.action) else: old_value, old_action = attrs[self.attr] if old_action != 'override': attrs[self.attr] = ('{} {}'.format(old_value, value), self.action)
class WidgetAttrsNode(Node): """ Renders attrs for the html tag. <input{% attrs boundfield 'widget' default field.widget.attrs %} id="id_{{ bound_field.name }}" class="{% if bound_field.errors %}invalid{% endif %}" {% endattrs %}> """ def __init__(self, parser, token): # noqa D102 bits = token.split_contents() if len(bits) < 3: raise TemplateSyntaxError( "%r accepts at least 2 arguments (bound_field," " 'groupname'), got: {}".format(bits[0], ','.join(bits[1:])) ) if len(bits) > 5: raise TemplateSyntaxError( "%r accepts at mast 4 arguments (bound_field, 'groupname'" " default attrs_dict ), got: {}".format( bits[0], ','.join(bits[1:])) ) if len(bits) > 3 and bits[3] != 'default': raise TemplateSyntaxError( "%r 3d argument should be 'default' (bound_field, 'groupname'" " default attrs_dict ), got: {}".format( bits[0], ','.join(bits[1:])) ) self.field = Variable(bits[1]) self.group = Variable(bits[2]) self.widget_attrs = Variable(bits[4]) if len(bits) >= 5 else None self.nodelist = parser.parse(('end{}'.format(bits[0]))) parser.delete_first_token() def resolve_field(self, context): """Resolve field reference form context.""" field = self.field.resolve(context) if isinstance(field, BoundField): field = field.field return field def render(self, context): # noqa D102 field = self.resolve_field(context) group = self.group.resolve(context) form_widget_attrs = context['form_widget_attrs'] override = {} if group in form_widget_attrs[field]: override = form_widget_attrs[field][group] build_in_attrs, tag_content = {}, self.nodelist.render(context) for attr, _, value in ATTRS_RE.findall(tag_content): build_in_attrs[attr] = mark_safe(value) if value != '' else True widget_attrs = {} if self.widget_attrs is not None: widget_attrs = self.widget_attrs.resolve(context) result = build_in_attrs.copy() if 'class' in result and 'class' in widget_attrs: result['class'] += ' ' + widget_attrs.pop('class') result.update(widget_attrs) for attr, (value, action) in override.items(): if action == 'override': result[attr] = value elif action == 'append': if attr in result: result[attr] += " " + value else: result[attr] = value return flatatt(result)
def __init__(self, ab_test_name, variant_a_content, variant_b_content): self.ab_test_name = Variable(ab_test_name) self.variant_a_content = variant_a_content self.variant_b_content = variant_b_content
class WidgetAttrNode(Node): """The tag allows to add or override specific attribute in the rendered HTML. The first argumnent is the attribute group name, second is the attribute name. The third optional flag shows to override (by default) or `append` the value. Usage:: {% attr form.email 'widget' 'data-validate' %}email{% endattr %} {% attr form.email 'widget' 'class' append %}green{% endattr %} {% attr form.email 'widget' 'required' %}True{% endattr %} """ def __init__(self, parser, token): # noqa D102 bits = token.split_contents() if len(bits) < 4: raise TemplateSyntaxError( "{} accepts at least 3 arguments (bound_field, 'groupname'" " 'attr_name'), got: {}".format(bits[0], ','.join(bits[1:])) ) if len(bits) > 5: raise TemplateSyntaxError( "{} accepts at mast 4 arguments (bound_field, 'groupname'" " 'attr_name' action ), got: {}".format( bits[0], ','.join(bits[1:])) ) if len(bits) >= 5 and bits[4] not in ['append', 'override']: raise TemplateSyntaxError( "{} unknown action {} should be 'append'" " of 'override'".format(bits[0], ','.join(bits[4])) ) self.field = Variable(bits[1]) self.group = Variable(bits[2]) self.attr = bits[3] self.action = bits[4] if len(bits) >= 5 else 'override' self.nodelist = parser.parse(('end{}'.format(bits[0]))) parser.delete_first_token() def resolve_field(self, context): """Resolve field reference form context.""" field = self.field.resolve(context) if isinstance(field, BoundField): field = field.field return field def render(self, context): # noqa D102 field = self.resolve_field(context) group = self.group.resolve(context) form_widget_attrs = context['form_widget_attrs'] value = self.nodelist.render(context) if group not in form_widget_attrs[field]: form_widget_attrs[field][group] = {} attrs = form_widget_attrs[field][group] if self.attr not in attrs or self.action == 'override': attrs[self.attr] = (value, self.action) else: old_value, old_action = attrs[self.attr] if old_action != 'override': attrs[self.attr] = ( '{} {}'.format(old_value, value), self.action )
def dictsort(value, arg): """ Takes a list of dicts, returns that list sorted by the property given in the argument. """ return sorted(value, key=Variable(arg).resolve)
class WidgetAttrsNode(Node): """ Renders attrs for the html tag. <input{% attrs boundfield 'widget' default field.widget.attrs %} id="id_{{ bound_field.name }}" class="{% if bound_field.errors %}invalid{% endif %}" {% endattrs %}> """ def __init__(self, parser, token): bits = token.split_contents() if len(bits) < 3: raise TemplateSyntaxError( "%r accepts at least 2 arguments (bound_field, 'groupname'), got: {}" % (bits[0], ','.join(bits[1:]))) if len(bits) > 5: raise TemplateSyntaxError( "%r accepts at mast 4 arguments (bound_field, 'groupname' default attrs_dict ), got: {}" % (bits[0], ','.join(bits[1:]))) if len(bits) > 3 and bits[3] != 'default': raise TemplateSyntaxError( "%r 3d argument should be 'default' (bound_field, 'groupname' default attrs_dict ), got: {}" % (bits[0], ','.join(bits[1:]))) self.field = Variable(bits[1]) self.group = Variable(bits[2]) self.widget_attrs = Variable(bits[4]) if len(bits) >= 5 else None self.nodelist = parser.parse(('end{}'.format(bits[0]), )) parser.delete_first_token() def resolve_field(self, context): field = self.field.resolve(context) if isinstance(field, BoundField): field = field.field return field def render(self, context): field = self.resolve_field(context) group = self.group.resolve(context) form_widget_attrs = context['form_widget_attrs'] override = {} if group in form_widget_attrs[field]: override = form_widget_attrs[field][group] build_in_attrs, tag_content = {}, self.nodelist.render(context) for attr, _, value in ATTRS_RE.findall(tag_content): build_in_attrs[attr] = value if value != '' else True widget_attrs = {} if self.widget_attrs is not None: widget_attrs = self.widget_attrs.resolve(context) result = build_in_attrs.copy() if 'class' in result and 'class' in widget_attrs: result['class'] += ' ' + widget_attrs.pop('class') result.update(widget_attrs) for attr, (value, action) in override.items(): if action == 'override': result[attr] = value elif action == 'append': if attr in result: result[attr] += " " + value else: result[attr] = value return flatatt(result)
def do_replace(match): return Variable(match.group(1)).resolve(self)
def render(self, context): kwargs = {} for key in self.kwargs: kwargs[key] = Variable(self.kwargs[key]).resolve(context) query_list = Variable(self.query_list_name).resolve(context) return query_list.filter(**kwargs)
import os import sys sys.path.append( os.path.join(os.path.dirname(__file__), "../integration/django")) from django.template.base import Variable for i in xrange(400000): Variable(u"model.name")