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

Тел: +7 965 3737 888





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

Ответы (1):

Ответ полезен? Да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 %}