Python django.utils.translation 模块,pgettext() 实例源码

我们从Python开源项目中,提取了以下28个代码示例,用于说明如何使用django.utils.translation.pgettext()

项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def validate_voucher(view):
    """Decorate a view making it check whether a discount voucher is valid.

    If the voucher is invalid it will be removed and the user will be
    redirected to the checkout summary view.
    """
    @wraps(view)
    def func(request, checkout, cart):
        if checkout.voucher_code:
            try:
                Voucher.objects.active().get(code=checkout.voucher_code)
            except Voucher.DoesNotExist:
                del checkout.voucher_code
                checkout.recalculate_discount()
                msg = pgettext(
                    'Checkout warning',
                    'This voucher has expired. Please review your checkout.')
                messages.warning(request, msg)
                return redirect('checkout:summary')
        return view(request, checkout, cart)
    return func
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def __str__(self):
        if self.name:
            return self.name
        discount = '%s %s' % (
            self.discount_value, self.get_discount_value_type_display())
        if self.type == Voucher.SHIPPING_TYPE:
            if self.is_free:
                return pgettext('Voucher type', 'Free shipping')
            else:
                return pgettext('Voucher type', '%(discount)s off shipping') % {
                    'discount': discount}
        if self.type == Voucher.PRODUCT_TYPE:
            return pgettext('Voucher type', '%(discount)s off %(product)s') % {
                'discount': discount, 'product': self.product}
        if self.type == Voucher.CATEGORY_TYPE:
            return pgettext('Voucher type', '%(discount)s off %(category)s') % {
                'discount': discount, 'category': self.category}
        return pgettext('Voucher type', '%(discount)s off') % {'discount': discount}
项目:pretalx    作者:pretalx    | 项目源码 | 文件源码
def _set_state(self, new_state, force=False):
        """
        check if the new state is valid for this Submission (based on SubmissionStates.valid_next_states).
        if yes, set it and save the object. if no, raise a SubmissionError with a helpful message.
        """

        valid_next_states = SubmissionStates.valid_next_states.get(self.state, [])

        if new_state in valid_next_states or force:
            self.state = new_state
            self.save(update_fields=['state'])
        else:
            source_states = (src for src, dsts in SubmissionStates.valid_next_states.items() if new_state in dsts)

            # build an error message mentioning all states, which are valid source states for the desired new state.
            trans_or = pgettext('used in talk confirm/accept/reject/...-errors, like "... must be accepted OR foo OR bar ..."', ' or ')
            state_names = dict(SubmissionStates.get_choices())
            source_states = trans_or.join(str(state_names[state]) for state in source_states)
            raise SubmissionError(
                _('Submission must be {src_states} not {state} to be {new_state}.').format(
                    src_states=source_states, state=self.state, new_state=new_state
                )
            )
项目:pretalx    作者:pretalx    | 项目源码 | 文件源码
def render_label(content, label_for=None, label_class=None, label_title='', optional=False):
    """
    Render a label with content
    """
    attrs = {}
    if label_for:
        attrs['for'] = label_for
    if label_class:
        attrs['class'] = label_class
    if label_title:
        attrs['title'] = label_title
    builder = '<{tag}{attrs}>{content}{opt}</{tag}>'
    return format_html(
        builder,
        tag='label',
        attrs=mark_safe(flatatt(attrs)) if attrs else '',
        opt=mark_safe('<br><span class="optional">{}</span>'.format(pgettext('form', 'Optional'))) if optional else '',
        content=text_value(content),
    )
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def add_truncation_text(self, text, truncate=None):
        if truncate is None:
            truncate = pgettext(
                'String to return when truncating text',
                '%(truncated_text)s...')
        truncate = force_text(truncate)
        if '%(truncated_text)s' in truncate:
            return truncate % {'truncated_text': text}
        # The truncation text didn't contain the %(truncated_text)s string
        # replacement argument so just append it to the text.
        if text.endswith(truncate):
            # But don't append the truncation text if the current text already
            # ends in this.
            return text
        return '%s%s' % (text, truncate)
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def handle_order_placement(request, checkout):
    """Try to create an order and redirect the user as necessary.

    This is a helper function.
    """
    order, redirect = create_order(checkout)
    if not order:
        msg = pgettext('Checkout warning', 'Please review your checkout.')
        messages.warning(request, msg)
    return redirect
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def get_or_process_password_form(request):
    form = ChangePasswordForm(data=request.POST or None, user=request.user)
    if form.is_valid():
        form.save()
        logout_on_password_change(request, form.user)
        messages.success(request, pgettext(
            'Storefront message', 'Password successfully changed.'))
    return form
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def address_edit(request, pk):
    address = get_object_or_404(request.user.addresses, pk=pk)
    address_form, preview = get_address_form(
        request.POST or None, instance=address,
        country_code=address.country.code)
    if address_form.is_valid() and not preview:
        address_form.save()
        message = pgettext('Storefront message', 'Address successfully updated.')
        messages.success(request, message)
        return HttpResponseRedirect(reverse('profile:details') + '#addresses')
    return TemplateResponse(
        request, 'userprofile/address-edit.html',
        {'address_form': address_form})
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def address_delete(request, pk):
    address = get_object_or_404(request.user.addresses, pk=pk)
    if request.method == 'POST':
        address.delete()
        messages.success(
            request,
            pgettext('Storefront message', 'Address successfully deleted.'))
        return HttpResponseRedirect(reverse('profile:details') + '#addresses')
    return TemplateResponse(
        request, 'userprofile/address-delete.html', {'address': address})
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def get_apply_to_display(self):
        if self.type == Voucher.SHIPPING_TYPE and self.apply_to:
            return countries.name(self.apply_to)
        if self.type == Voucher.SHIPPING_TYPE:
            return pgettext('Voucher', 'Any country')
        if self.apply_to and self.type in {
                Voucher.PRODUCT_TYPE, Voucher.CATEGORY_TYPE}:
            choices = dict(self.APPLY_TO_PRODUCT_CHOICES)
            return choices[self.apply_to]
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def validate_limit(self, value):
        limit = self.limit if self.limit is not None else value
        if value < limit:
            msg = pgettext(
                'Voucher not applicable', 'This offer is only valid for orders over %(amount)s.')
            raise NotApplicable(msg % {'amount': net(limit)})
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def modifier_for_product(self, product):
        discounted_products = {p.pk for p in self.products.all()}
        discounted_categories = set(self.categories.all())
        if product.pk in discounted_products:
            return self.get_discount()
        if self._product_has_category_discount(
                product, discounted_categories):
            return self.get_discount()
        raise NotApplicable(
            pgettext(
                'Voucher not applicable', 'Discount not applicable for this product'))
项目:feincms3    作者:matthiask    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self.instance = kwargs.pop('obj')
        self.model = self.instance.__class__

        super(MoveForm, self).__init__(*args, **kwargs)

        self.fields['of'] = forms.ModelChoiceField(
            label=pgettext('MoveForm', 'Of'),
            required=False,
            queryset=self.model.objects.exclude(
                pk__in=self.instance.descendants(),
            ),
            widget=forms.Select(attrs={'size': 30, 'style': 'height:auto'}),
        )

        self.fields['of'].choices = [
            (None, '----------'),
        ] + [
            (
                obj.pk,
                '%s%s' % (
                    (obj.depth - 1) * (
                        '*** ' if obj == self.instance else '--- '),
                    obj,
                ),
            ) for obj in self.fields['of'].queryset
        ]
项目:django-twilio-tfa    作者:rtindru    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(LoginForm, self).__init__(*args, **kwargs)
        if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL:
            login_widget = forms.TextInput(attrs={'type': 'email',
                                                  'placeholder':
                                                  _('E-mail address'),
                                                  'autofocus': 'autofocus'})
            login_field = forms.EmailField(label=_("E-mail"),
                                           widget=login_widget)
        elif app_settings.AUTHENTICATION_METHOD \
                == AuthenticationMethod.USERNAME:
            login_widget = forms.TextInput(attrs={'placeholder':
                                                  _('Username'),
                                                  'autofocus': 'autofocus'})
            login_field = forms.CharField(
                label=_("Username"),
                widget=login_widget,
                max_length=get_username_max_length())
        else:
            assert app_settings.AUTHENTICATION_METHOD \
                == AuthenticationMethod.USERNAME_EMAIL
            login_widget = forms.TextInput(attrs={'placeholder':
                                                  _('Username or e-mail'),
                                                  'autofocus': 'autofocus'})
            login_field = forms.CharField(label=pgettext("field label",
                                                         "Login"),
                                          widget=login_widget)
        self.fields["login"] = login_field
        set_form_field_order(self,  ["login", "password", "remember"])
        if app_settings.SESSION_REMEMBER is not None:
            del self.fields['remember']
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def add_truncation_text(self, text, truncate=None):
        if truncate is None:
            truncate = pgettext(
                'String to return when truncating text',
                '%(truncated_text)s...')
        truncate = force_text(truncate)
        if '%(truncated_text)s' in truncate:
            return truncate % {'truncated_text': text}
        # The truncation text didn't contain the %(truncated_text)s string
        # replacement argument so just append it to the text.
        if text.endswith(truncate):
            # But don't append the truncation text if the current text already
            # ends in this.
            return text
        return '%s%s' % (text, truncate)
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def add_truncation_text(self, text, truncate=None):
        if truncate is None:
            truncate = pgettext(
                'String to return when truncating text',
                '%(truncated_text)s...')
        truncate = force_text(truncate)
        if '%(truncated_text)s' in truncate:
            return truncate % {'truncated_text': text}
        # The truncation text didn't contain the %(truncated_text)s string
        # replacement argument so just append it to the text.
        if text.endswith(truncate):
            # But don't append the truncation text if the current text already
            # ends in this.
            return text
        return '%s%s' % (text, truncate)
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def add_truncation_text(self, text, truncate=None):
        if truncate is None:
            truncate = pgettext(
                'String to return when truncating text',
                '%(truncated_text)s...')
        truncate = force_text(truncate)
        if '%(truncated_text)s' in truncate:
            return truncate % {'truncated_text': text}
        # The truncation text didn't contain the %(truncated_text)s string
        # replacement argument so just append it to the text.
        if text.endswith(truncate):
            # But don't append the truncation text if the current text already
            # ends in this.
            return text
        return '%s%s' % (text, truncate)
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
def add_truncation_text(self, text, truncate=None):
        if truncate is None:
            truncate = pgettext(
                'String to return when truncating text',
                '%(truncated_text)s...')
        truncate = force_text(truncate)
        if '%(truncated_text)s' in truncate:
            return truncate % {'truncated_text': text}
        # The truncation text didn't contain the %(truncated_text)s string
        # replacement argument so just append it to the text.
        if text.endswith(truncate):
            # But don't append the truncation text if the current text already
            # ends in this.
            return text
        return '%s%s' % (text, truncate)
项目:Provo-Housing-Database    作者:marcopete5    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        if app_settings.AUTHENTICATION_METHOD == AuthenticationMethod.EMAIL:
            login_widget = forms.TextInput(attrs={'type': 'email',
                                                  'placeholder':
                                                  _('E-mail address'),
                                                  'autofocus': 'autofocus'})
            login_field = forms.EmailField(label=_("E-mail"),
                                           widget=login_widget)
        elif app_settings.AUTHENTICATION_METHOD \
                == AuthenticationMethod.USERNAME:
            login_widget = forms.TextInput(attrs={'placeholder':
                                                  _('Username'),
                                                  'autofocus': 'autofocus'})
            login_field = forms.CharField(
                label=_("Username"),
                widget=login_widget,
                max_length=get_username_max_length())
        else:
            assert app_settings.AUTHENTICATION_METHOD \
                == AuthenticationMethod.USERNAME_EMAIL
            login_widget = forms.TextInput(attrs={'placeholder':
                                                  _('Username or e-mail'),
                                                  'autofocus': 'autofocus'})
            login_field = forms.CharField(label=pgettext("field label",
                                                         "Login"),
                                          widget=login_widget)
        self.fields["login"] = login_field
        set_form_field_order(self,  ["login", "password", "remember"])
        if app_settings.SESSION_REMEMBER is not None:
            del self.fields['remember']
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
def add_truncation_text(self, text, truncate=None):
        if truncate is None:
            truncate = pgettext(
                'String to return when truncating text',
                '%(truncated_text)s...')
        truncate = force_text(truncate)
        if '%(truncated_text)s' in truncate:
            return truncate % {'truncated_text': text}
        # The truncation text didn't contain the %(truncated_text)s string
        # replacement argument so just append it to the text.
        if text.endswith(truncate):
            # But don't append the truncation text if the current text already
            # ends in this.
            return text
        return '%s%s' % (text, truncate)
项目:newco-legacy    作者:blaze33    | 项目源码 | 文件源码
def update_kwargs(key, request, **kwargs):
    WORDS = {"object-created": "created", "object-updated": "updated"}

    kwargs.update({"user": user_display(request.user)})
    if "model" in kwargs:
        model = kwargs.pop("model")
        kwargs.update({"article": pgettext(model._meta.module_name, "the "),
                       "verbose_name": model._meta.verbose_name})
        if key in WORDS:
            word = WORDS[key]
            kwargs.update({word: pgettext(model._meta.module_name, word)})
    return kwargs
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        tmp_context = {}
        for var, val in self.extra_context.items():
            tmp_context[var] = val.resolve(context)
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update(tmp_context)
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ungettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                result = translation.ugettext(singular)
        default_value = context.template.engine.string_if_invalid

        def render_value(key):
            if key in context:
                val = context[key]
            else:
                val = default_value % key if '%s' in default_value else default_value
            return render_value_in_context(val, context)

        data = {v: render_value(v) for v in vars}
        context.pop()
        try:
            result = result % data
        except (KeyError, ValueError):
            if nested:
                # Either string is malformed, or it's a bug
                raise TemplateSyntaxError("'blocktrans' is unable to format "
                    "string returned by gettext: %r using %r" % (result, data))
            with translation.override(None):
                result = self.render(context, nested=True)
        if self.asvar:
            context[self.asvar] = result
            return ''
        else:
            return result
项目:planet-b-saleor    作者:planet-b    | 项目源码 | 文件源码
def get_discount_for_checkout(self, checkout):
        if self.type == Voucher.VALUE_TYPE:
            cart_total = checkout.get_subtotal()
            self.validate_limit(cart_total)
            return self.get_fixed_discount_for(cart_total)

        elif self.type == Voucher.SHIPPING_TYPE:
            if not checkout.is_shipping_required:
                msg = pgettext(
                    'Voucher not applicable', 'Your order does not require shipping.')
                raise NotApplicable(msg)
            shipping_method = checkout.shipping_method
            if not shipping_method:
                msg = pgettext(
                    'Voucher not applicable', 'Please select a shipping method first.')
                raise NotApplicable(msg)
            if (self.apply_to and
                    shipping_method.country_code != self.apply_to):
                msg = pgettext(
                    'Voucher not applicable', 'This offer is only valid in %(country)s.')
                raise NotApplicable(msg % {
                    'country': self.get_apply_to_display()})
            cart_total = checkout.get_subtotal()
            self.validate_limit(cart_total)
            return self.get_fixed_discount_for(shipping_method.price)

        elif self.type in (Voucher.PRODUCT_TYPE, Voucher.CATEGORY_TYPE):
            if self.type == Voucher.PRODUCT_TYPE:
                prices = list(
                    (item[1] for item in get_product_variants_and_prices(
                        checkout.cart, self.product)))
            else:
                prices = list(
                    (item[1] for item in get_category_variants_and_prices(
                        checkout.cart, self.category)))
            if len(prices) == 0:
                msg = pgettext(
                    'Voucher not applicable',
                    'This offer is only valid for selected items.')
                raise NotApplicable(msg)
            if self.apply_to == Voucher.APPLY_TO_ALL_PRODUCTS:
                discounts = (
                    self.get_fixed_discount_for(price) for price in prices)
                discount_total = sum(
                    (discount.amount for discount in discounts),
                    Price(0, currency=settings.DEFAULT_CURRENCY))
                return FixedDiscount(discount_total, smart_text(self))
            else:
                product_total = sum(
                    prices, Price(0, currency=settings.DEFAULT_CURRENCY))
                return self.get_fixed_discount_for(product_total)

        else:
            raise NotImplementedError('Unknown discount type')
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        tmp_context = {}
        for var, val in self.extra_context.items():
            tmp_context[var] = val.resolve(context)
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update(tmp_context)
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ungettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                result = translation.ugettext(singular)
        default_value = context.template.engine.string_if_invalid

        def render_value(key):
            if key in context:
                val = context[key]
            else:
                val = default_value % key if '%s' in default_value else default_value
            return render_value_in_context(val, context)

        data = {v: render_value(v) for v in vars}
        context.pop()
        try:
            result = result % data
        except (KeyError, ValueError):
            if nested:
                # Either string is malformed, or it's a bug
                raise TemplateSyntaxError(
                    "'blocktrans' is unable to format string returned by gettext: %r using %r"
                    % (result, data)
                )
            with translation.override(None):
                result = self.render(context, nested=True)
        if self.asvar:
            context[self.asvar] = result
            return ''
        else:
            return result
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        tmp_context = {}
        for var, val in self.extra_context.items():
            tmp_context[var] = val.resolve(context)
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update(tmp_context)
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ungettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                result = translation.ugettext(singular)
        default_value = context.template.engine.string_if_invalid

        def render_value(key):
            if key in context:
                val = context[key]
            else:
                val = default_value % key if '%s' in default_value else default_value
            return render_value_in_context(val, context)

        data = {v: render_value(v) for v in vars}
        context.pop()
        try:
            result = result % data
        except (KeyError, ValueError):
            if nested:
                # Either string is malformed, or it's a bug
                raise TemplateSyntaxError("'blocktrans' is unable to format "
                    "string returned by gettext: %r using %r" % (result, data))
            with translation.override(None):
                result = self.render(context, nested=True)
        if self.asvar:
            context[self.asvar] = result
            return ''
        else:
            return result
项目:tissuelab    作者:VirtualPlants    | 项目源码 | 文件源码
def naturaltime(value):
    """
    For date and time values shows how many seconds, minutes or hours ago
    compared to current timestamp returns representing string.
    """
    if not isinstance(value, date): # datetime is a subclass of date
        return value

    now = datetime.now(utc if is_aware(value) else None)
    if value < now:
        delta = now - value
        if delta.days != 0:
            return pgettext(
                'naturaltime', '%(delta)s ago'
            ) % {'delta': defaultfilters.timesince(value, now)}
        elif delta.seconds == 0:
            return _('now')
        elif delta.seconds < 60:
            return ungettext(
                # Translators: \\u00a0 is non-breaking space
                'a second ago', '%(count)s\u00a0seconds ago', delta.seconds
            ) % {'count': delta.seconds}
        elif delta.seconds // 60 < 60:
            count = delta.seconds // 60
            return ungettext(
                # Translators: \\u00a0 is non-breaking space
                'a minute ago', '%(count)s\u00a0minutes ago', count
            ) % {'count': count}
        else:
            count = delta.seconds // 60 // 60
            return ungettext(
                # Translators: \\u00a0 is non-breaking space
                'an hour ago', '%(count)s\u00a0hours ago', count
            ) % {'count': count}
    else:
        delta = value - now
        if delta.days != 0:
            return pgettext(
                'naturaltime', '%(delta)s from now'
            ) % {'delta': defaultfilters.timeuntil(value, now)}
        elif delta.seconds == 0:
            return _('now')
        elif delta.seconds < 60:
            return ungettext(
                # Translators: \\u00a0 is non-breaking space
                'a second from now', '%(count)s\u00a0seconds from now', delta.seconds
            ) % {'count': delta.seconds}
        elif delta.seconds // 60 < 60:
            count = delta.seconds // 60
            return ungettext(
                # Translators: \\u00a0 is non-breaking space
                'a minute from now', '%(count)s\u00a0minutes from now', count
            ) % {'count': count}
        else:
            count = delta.seconds // 60 // 60
            return ungettext(
                # Translators: \\u00a0 is non-breaking space
                'an hour from now', '%(count)s\u00a0hours from now', count
            ) % {'count': count}
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        tmp_context = {}
        for var, val in self.extra_context.items():
            tmp_context[var] = val.resolve(context)
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update(tmp_context)
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ungettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                result = translation.ugettext(singular)
        default_value = context.template.engine.string_if_invalid

        def render_value(key):
            if key in context:
                val = context[key]
            else:
                val = default_value % key if '%s' in default_value else default_value
            return render_value_in_context(val, context)

        data = {v: render_value(v) for v in vars}
        context.pop()
        try:
            result = result % data
        except (KeyError, ValueError):
            if nested:
                # Either string is malformed, or it's a bug
                raise TemplateSyntaxError("'blocktrans' is unable to format "
                    "string returned by gettext: %r using %r" % (result, data))
            with translation.override(None):
                result = self.render(context, nested=True)
        if self.asvar:
            context[self.asvar] = result
            return ''
        else:
            return result
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
def render(self, context, nested=False):
        if self.message_context:
            message_context = self.message_context.resolve(context)
        else:
            message_context = None
        tmp_context = {}
        for var, val in self.extra_context.items():
            tmp_context[var] = val.resolve(context)
        # Update() works like a push(), so corresponding context.pop() is at
        # the end of function
        context.update(tmp_context)
        singular, vars = self.render_token_list(self.singular)
        if self.plural and self.countervar and self.counter:
            count = self.counter.resolve(context)
            context[self.countervar] = count
            plural, plural_vars = self.render_token_list(self.plural)
            if message_context:
                result = translation.npgettext(message_context, singular,
                                               plural, count)
            else:
                result = translation.ungettext(singular, plural, count)
            vars.extend(plural_vars)
        else:
            if message_context:
                result = translation.pgettext(message_context, singular)
            else:
                result = translation.ugettext(singular)
        default_value = context.template.engine.string_if_invalid

        def render_value(key):
            if key in context:
                val = context[key]
            else:
                val = default_value % key if '%s' in default_value else default_value
            return render_value_in_context(val, context)

        data = {v: render_value(v) for v in vars}
        context.pop()
        try:
            result = result % data
        except (KeyError, ValueError):
            if nested:
                # Either string is malformed, or it's a bug
                raise TemplateSyntaxError("'blocktrans' is unable to format "
                    "string returned by gettext: %r using %r" % (result, data))
            with translation.override(None):
                result = self.render(context, nested=True)
        return result