本文整理汇总了Python中django.template.base.Variable类的典型用法代码示例。如果您正苦于以下问题:Python Variable类的具体用法?Python Variable怎么用?Python Variable使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Variable类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
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()
示例2: render
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 ''
示例3: FormPartNode
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
示例4: render
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 ''
示例5: WidgetAttrNode
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)
示例6: render
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 ''
示例7: _ABTestNode
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!")
示例8: __init__
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])
示例9: render
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)
示例10: FormRenderNode
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, ))
示例11: __init__
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()
示例12: IncludeNode
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:
示例13: FormPartNode
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
示例14: __init__
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
示例15: WidgetAttrNode
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
)