Вы смешиваете два подхода здесь.simple_tag
- это просто вспомогательная функция, которая сокращает некоторый шаблонный код и должна возвращать строку.Чтобы установить контекстные переменные, вам нужно (по крайней мере, с простым django) написать свой собственный тег с помощью метода рендеринга.
from django import template
register = template.Library()
class FooNode(template.Node):
def __init__(self, obj):
# saves the passed obj parameter for later use
# this is a template.Variable, because that way it can be resolved
# against the current context in the render method
self.object = template.Variable(obj)
def render(self, context):
# resolve allows the obj to be a variable name, otherwise everything
# is a string
obj = self.object.resolve(context)
# obj now is the object you passed the tag
context['var'] = 'somevar'
return ''
@register.tag
def do_foo(parser, token):
# token is the string extracted from the template, e.g. "do_foo my_object"
# it will be splitted, and the second argument will be passed to a new
# constructed FooNode
try:
tag_name, obj = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires exactly one argument" % token.contents.split()[0]
return FooNode(obj)
Это можно назвать так:
{% do_foo my_object %}
{% do_foo 25 %}