Skip to main content
 首页 » 编程设计

python之从普通函数调用 django 模板标签

2025年05月04日12youxin

如何从普通函数中调用django模板标签?

例如:

Django 模板标签:

@register.filter(name='CallingTemplateTagFunction') 
def CallingTemplateTagFunction(price):     
    return price*10/100 

我想在普通函数中调用 GetValue 函数。

例如:

普通python函数:

def Test(request): 
    CallingTemplateTagFunction(50) # How to call django template tag function? 

请您参考如下方法:

你可以在某处写下你的函数:

def my_useful_function(price): 
    return price * 10 / 100 

然后在您的 View 和模板标签中使用它:

from somewhere import my_useful_function 
 
# in templatetags:     
@register.filter(name='calling_template_tag_function') 
def calling_template_tag_function(price):     
    return my_useful_function(price) 

然后在 View 中:

def test(request): 
   my_useful_function(50)