【问题标题】:Call methods in Django Template [duplicate]Django模板中的调用方法[重复]
【发布时间】:2014-04-06 06:48:24
【问题描述】:

我的视图给我一个列表或报告和当前用户

在我想要做的模板中:

{% for report in reports %}
    ...
    {% if current_user.can_edit_report(report) == True %}
       ...
    {% endif %}
    ...
{% endfor %}

但这会引发错误

Could not parse the remainder: '(report)' from 'current_user.can_edit_report(report)'

因为 Django 似乎无法在模板中调用带有参数的方法。

所以我必须在视图中这样做...

你知道如何正确地做到这一点吗?

谢谢

【问题讨论】:

标签: django django-templates


【解决方案1】:

是的,如上所述,这个问题有重复 (How to call function that takes an argument in a Django template?)。

您要做的是像这样创建一个自定义模板标签 (https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags)...

# template
<p>Can Edit: {% can_edit_report user_id report_id %}.</p>

# template_tags.py
from django import template

def can_edit_report(parser, token):
    try:
        # tag_name is 'can_edit_report'
        tag_name, user_id, report_id = token.split_contents()
        # business logic here (can user edit this report?)
        user = User.objects.get(pk=user_id)
        report = Report.objects.get(pk=report_id)
        can_edit = user.can_edit_report(report)
    except ValueError:
        raise template.TemplateSyntaxError("%r tag requires two arguments" % token.contents.split()[0])
    return can_edit

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-28
    • 2020-04-10
    • 1970-01-01
    • 2016-11-17
    • 2014-05-17
    • 2013-07-24
    • 1970-01-01
    • 2020-09-06
    相关资源
    最近更新 更多