【问题标题】:pass two value to a template tag将两个值传递给模板标签
【发布时间】:2019-08-25 23:18:33
【问题描述】:

我是 django 和 python 的新手。在我的模板中,我需要将两个值传递给模板标签。这两个值来自view.py。我读过Django template, send two arguments to template tag?,但我可以解决我的问题。

view.py:

def order(request):
   .
   .
   . 
 return render(request, 'cart.html', {
                "total_price": total_price,
                "final_verified": profile.teacher.final_verified,
                "cart": the_cart,
                "cart_items": the_cart.cartitem_set.filter(deleted=False),
                "discount": discount
            })

模板.html:

{% load tags %}

 <div class="pull-left">
                      <i>
                        {% if final_verified %}
                          {{ total_price|rials_to_toman|intcomma:False }}
                          {%  final_price total_price discount %} <!--problem is here-->
                        {% else %}
                          0
                        {% endif %}
                       </i>Price
 </div>

tag.py:

from django import template
register = template.Library()

@register.simple_tag
def final_price(num,discount):   
    return str((int(num) * int(discount)) // 100)

@register.filter
def rich_to_pay_calc(num):
    if num:
        return str((int(num)*8 // 10) + 3000)
    else:
        return ""

@register.filter
def percent_80(num):
    if num:
        return str((int(num) * 8) // 10)
    else:
        return ""


@register.filter
def truncate(num):
    num = str(num)
    return num[:3]

首先我在模板顶部使用了 {%load final_price%},但是当我尝试加载此模板的 url 时出现此错误:

TemplateSyntaxError at /order/cart/
'final_price' is not a registered tag library. Must be one of:
admin_list
admin_modify
admin_static
admin_urls
cache
humanize
i18n
l10n
log
static
staticfiles
tags
tz

在 tags.py 中存在一些其他标签(如上面的代码你可以看到)。有趣的是,模板中可以访问其他标签,除了 final_price 是 "simple_tag" 而不是 "filter" 。我是 django 和 web 开发的新手,如果问题很愚蠢,请原谅。 tnx

【问题讨论】:

  • 如果您在模板开头使用{% load final_price %},它会起作用吗?
  • 你说问题发生在哪里,但你似乎没有说它实际上是什么。使用该标签时会发生什么?
  • @drec4s : tnx 但不起作用。
  • @DanielRoseman:问题已更新。请再检查一次。 tnx

标签: django templatetags


【解决方案1】:

由于您使用了简单标签,我认为您需要将标签名称本身加载为:

 {% load final_price %} <--add

 <div class="pull-left">
         <i>
         {% if final_verified %}
             {{ total_price|rials_to_toman|intcomma:False }}
             {% final_price total_price discount %}
                    {% else %}
                      0
                    {% endif %}
                   </i>Price
</div>

希望有效果

【讨论】:

  • 我以前做过,但没用。当我按下 ctrl+click 时,即使 pycharm 也不知道“final_price”的来源。
  • 确保你已经重启了 Django 开发服务器。
【解决方案2】:

template.html 中使用 {% load tag %} 而不是 {% load tags %}

【讨论】:

    猜你喜欢
    • 2019-02-15
    • 2016-02-15
    • 2017-03-02
    • 2012-09-27
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 2015-06-22
    相关资源
    最近更新 更多