如何在Django模板中使用方法参数?

时间:2009-10-07 04:58:40

标签: django django-templates

我知道这里有一篇帖子:django template system, calling a function inside a model描述了如何制作一个自定义模板过滤器来实现这一目标,但从程序员的角度来看,这是一个失败,因为这是一个不具备此功能的黑客攻击。你不能在Django的模板系统中调用带参数的方法似乎是荒谬的。

2 个答案:

答案 0 :(得分:40)

作为哲学问题,Django团队决定不允许在视图中传递方法参数。就个人而言,我同意他们的意见;它强制分离逻辑和演示文稿,我发现它很有帮助。它可以防止PHP因臭名昭着的意大利面条代码。

在链接的情况下,正确的做法是通过上下文将视图的调用结果传递给模板。这样可以更加可维护。如果以后需要将my_related_deltas(3)更改为my_related_deltas(4),则转到视图,该视图应该相当简洁,而不是搜索模板以确定其定义的确切位置。

答案 1 :(得分:13)

尽管django作者建议不用参数提供我们的方法,你仍然可以使用我写的这个'小'模板标签来做到这一点。

在我的例子中,我只是显示这是可能的。出于安全原因强烈建议编写模板标记,而不是尝试将参数传递给模型方法。

!警告!这仅用于测试目的!通过使用它你可能会入侵NASA以及你可能会被杀死。

class CallNode(template.Node):
    def __init__(self,object, method, args=None, kwargs=None, context_name=None):
        self.object = template.Variable(object)
        self.method = method
        if args:
            self.args = []
            for arg in args:
                self.args.append(template.Variable(arg))
        else:
            self.args = None

        if kwargs:
            self.kwargs = {}
            for key in kwargs:
                self.kwargs[key] = template.Variable(kwargs[key])
        else:
            self.kwargs = None

        self.context_name = context_name

    def render(self, context):
        object = self.object.resolve(context)
        if isinstance(object, str):
            raise template.TemplateSyntaxError('Given object is string ("%s") of length %d' 
                                               % (object, len(object)))

        args = []
        kwargs = {}
        if self.args:
            for arg in self.args:
                args.append(arg.resolve(context))
        if self.kwargs:
            for key in self.kwargs:
                kwargs[key] = self.kwargs[key].resolve(context)

        method = getattr(object, self.method, None)

        if method:
            if hasattr(method, '__call__'): 
                result = method(*args, **kwargs)
            else:
                result = method
            if self.context_name:
                context[self.context_name] = result
                return ''
            else:
                if not result == None: 
                    return result
                else:
                    return ''
        else:
            raise template.TemplateSyntaxError('Model %s doesn\'t have method "%s"' 
                                               % (object._meta.object_name, self.method))


@register.tag
def call(parser, token):
    """
    Passes given arguments to given method and returns result

    Syntax::

        {% call <object>[.<foreignobject>].<method or attribute> [with <*args> <**kwargs>] [as <context_name>] %}

    Example usage::

        {% call article.__unicode__ %}
        {% call article.get_absolute_url as article_url %}
        {% call article.is_visible with user %}
        {% call article.get_related with tag 5 as related_articles %}

        {% call object.foreign_object.test with other_object "some text" 123 article=article text="some text" number=123 as test %} 
    """

    bits = token.split_contents()
    syntax_message = ("%(tag_name)s expects a syntax of %(tag_name)s "
                       "<object>.<method or attribute> [with <*args> <**kwargs>] [as <context_name>]" %
                       dict(tag_name=bits[0]))

    temp = bits[1].split('.')
    method = temp[-1]
    object = '.'.join(temp[:-1])

    # Must have at least 2 bits in the tag
    if len(bits) > 2:
        try:
            as_pos = bits.index('as')
        except ValueError:
            as_pos = None
        try:
            with_pos = bits.index('with')
        except ValueError:
            with_pos = None

        if as_pos:
            context_name = bits[as_pos+1]
        else:
            context_name = None

        if with_pos:
            if as_pos:
                bargs = bits[with_pos+1:as_pos]
            else:
                bargs = bits[with_pos+1:]
        else:
            bargs = []

        args = []
        kwargs = {}

        if bargs:
            for barg in bargs:
                t = barg.split('=')
                if len(t) > 1:
                    kwargs[t[0]] = t[1]
                else:
                    args.append(t[0])

        return CallNode(object, method, args=args, kwargs=kwargs, context_name=context_name)
    elif len(bits) == 2:
        return CallNode(object, method)
    else:
        raise template.TemplateSyntaxError(syntax_message)