Задать вопрос

Тел: +7 965 3737 888

517

Просмотров

1

Ответов

Add parameters to the current url

Often a page contains a link to itself, with an additional parameter for in the url. E.g. to sort the page in a different way, to export the data into another format, etc... This tag makes this easy, avoiding any hardcoded urls in your pages.

Вопрос полезен? Да0/Нет0
file_2333.py(886.0б)
None

Ответы (1):

Ответludwik-trammer:16.02.2010
Ответ полезен? Да0/Нет0

If you want to be able to pass variables from template into the template tag you may use the following version:

from django.template import Library, Node, resolve_variable, TemplateSyntaxError, Variable

register = Library()

class AddParameter(Node):
  def __init__(self, varname, value):
    self.varname = Variable(varname)
    self.value = Variable(value)

  def render(self, context):
    req = Variable('request').resolve(context)
    params = req.GET.copy()
    params[self.varname.resolve(context)] = self.value.resolve(context)
    return '%s?%s' % (req.path, params.urlencode())

def addurlparameter(parser, token):
  from re import split
  bits = split(r'\s+', token.contents, 2)
  if len(bits) < 2:
    raise TemplateSyntaxError, "'%s' tag requires two arguments" % bits[0]
  return AddParameter(bits[1],bits[2])

register.tag('addurlparameter', addurlparameter)

Sample usage:

{% addurlparameter 'sort' variable %}