當前位置: 首頁>>代碼示例>>Python>>正文


Python base.Variable類代碼示例

本文整理匯總了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()
開發者ID:dmytrokyrychuk,項目名稱:django-material,代碼行數:25,代碼來源:material_form.py

示例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 ''
開發者ID:xSAVIKx,項目名稱:DjangoTest,代碼行數:7,代碼來源:extra_tags.py

示例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
開發者ID:strekmann,項目名稱:django-materialize,代碼行數:58,代碼來源:material_form.py

示例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 ''
開發者ID:ilblackdragon,項目名稱:django-misc,代碼行數:9,代碼來源:misc_tags.py

示例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)
開發者ID:strekmann,項目名稱:django-materialize,代碼行數:53,代碼來源:material_form.py

示例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 ''
開發者ID:tow,項目名稱:django-forms-builder,代碼行數:13,代碼來源:forms.py

示例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!")
開發者ID:euangoddard,項目名稱:django-ab,代碼行數:30,代碼來源:ab.py

示例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])
開發者ID:AnderLinares,項目名稱:django-material,代碼行數:27,代碼來源:material_form_internal.py

示例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)
開發者ID:yunmanger1,項目名稱:django-content-category,代碼行數:41,代碼來源:category_tags.py

示例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, ))
開發者ID:AliLozano,項目名稱:django-material,代碼行數:52,代碼來源:material_form_internal.py

示例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()
開發者ID:MgArreaza,項目名稱:Chat,代碼行數:13,代碼來源:material_form.py

示例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:
開發者ID:satyandrababu,項目名稱:django,代碼行數:14,代碼來源:loader_tags.py

示例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
開發者ID:MgArreaza,項目名稱:Chat,代碼行數:38,代碼來源:material_form.py

示例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
開發者ID:euangoddard,項目名稱:django-ab,代碼行數:4,代碼來源:ab.py

示例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
                )
開發者ID:dmytrokyrychuk,項目名稱:django-material,代碼行數:70,代碼來源:material_form.py


注:本文中的django.template.base.Variable類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。