Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Translatable strings #11

Open
foreverchild opened this issue Jan 6, 2011 · 0 comments
Open

Translatable strings #11

foreverchild opened this issue Jan 6, 2011 · 0 comments

Comments

@foreverchild
Copy link

Add possibility to translate strings in templates.

Just update "sorting_tags.py" with the following code

from django import template
from django.http import Http404
from django.conf import settings
from django.utils.translation import ugettext_lazy as _, ugettext as _f

register = template.Library()

DEFAULT_SORT_UP = getattr(settings, 'DEFAULT_SORT_UP' , '↑')
DEFAULT_SORT_DOWN = getattr(settings, 'DEFAULT_SORT_DOWN' , '↓')
INVALID_FIELD_RAISES_404 = getattr(settings,
'SORTING_INVALID_FIELD_RAISES_404' , False)

sort_directions = {
'asc': {'icon':DEFAULT_SORT_UP, 'inverse': 'desc'},
'desc': {'icon':DEFAULT_SORT_DOWN, 'inverse': 'asc'},
'': {'icon':DEFAULT_SORT_DOWN, 'inverse': 'asc'},
}

def anchor(parser, token):
"""
Parses a tag that's supposed to be in this format: {% anchor field title translate_title %}
"""
bits = [b.strip('"'') for b in token.split_contents()]
if len(bits) < 2:
raise TemplateSyntaxError, "anchor tag takes at least 1 argument"
try:
title = bits[2]
except IndexError:
title = bits[1].capitalize()
try:
translate_title = bool(bits[3])
except IndexError:
translate_title = True
return SortAnchorNode(bits[1].strip(), title.strip(), translate_title)

class SortAnchorNode(template.Node):
"""
Renders an HTML tag with a link which href attribute
includes the field on which we sort and the direction.
and adds an up or down arrow if the field is the one
currently being sorted on.

Eg.
    {% anchor name Name %} generates
    <a href="/the/current/path/?sort=name" title="Name">Name</a>

"""
def __init__(self, field, title, translate_title=True):
    self.field = field
    self.title = title
    self.translate_title = translate_title

def render(self, context):
    if self.translate_title:
        self.title = _f(self.title)
    request = context['request']
    getvars = request.GET.copy()
    if 'sort' in getvars:
        sortby = getvars['sort']
        del getvars['sort']
    else:
        sortby = ''
    if 'dir' in getvars:
        sortdir = getvars['dir']
        del getvars['dir']
    else:
        sortdir = ''
    if sortby == self.field:
        getvars['dir'] = sort_directions[sortdir]['inverse']
        icon = sort_directions[sortdir]['icon']
    else:
        icon = ''
    if len(getvars.keys()) > 0:
        urlappend = "&%s" % getvars.urlencode()
    else:
        urlappend = ''
    if icon:
        title = "%s %s" % (self.title, icon)
    else:
        title = self.title

    url = '%s?sort=%s%s' % (request.path, self.field, urlappend)
    return '<a href="%s" title="%s">%s</a>' % (url, self.title, title)

def autosort(parser, token):
bits = [b.strip('"'') for b in token.split_contents()]
if len(bits) != 2:
raise TemplateSyntaxError, "autosort tag takes exactly one argument"
return SortedDataNode(bits[1])

class SortedDataNode(template.Node):
"""
Automatically sort a queryset with {% autosort queryset %}
"""
def init(self, queryset_var, context_var=None):
self.queryset_var = template.Variable(queryset_var)
self.context_var = context_var

def render(self, context):
    key = self.queryset_var.var
    value = self.queryset_var.resolve(context)
    order_by = context['request'].field
    if len(order_by) > 1:
        try:
            context[key] = value.order_by(order_by)
        except template.TemplateSyntaxError:
            if INVALID_FIELD_RAISES_404:
                raise Http404('Invalid field sorting. If DEBUG were set to ' +
                'False, an HTTP 404 page would have been shown instead.')
            context[key] = value
    else:
        context[key] = value

    return ''

anchor = register.tag(anchor)
autosort = register.tag(autosort)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant