Skip to main content
 首页 » 编程设计

python之django 编写我的第一个自定义模板标签和过滤器

2025年05月04日30jackei

我正在尝试编写一个简单的 django Custom template tags and filters用模板上的行空间替换 html 分隔符 (< b r/>)。

我已按照 django 文档进行操作,但出现以下错误,我不知道如何解决。

我的错误是:

x_templates_extra' is not a valid tag library: Template library x_templates_extra not found, tried django.templatetags.x_templates_extra,django.contrib.staticfiles.templatetags.x_templates_extra,django.contrib.admin.templatetags.x_templates_extra,django.contrib.flatpages.templatetags.x_templates_extra,rosetta.templatetags.x_templates_extra,templatetag_handlebars.templatetags.x_templates_extra,globalx.common.templatetags.x_templates_extra,rollyourown.seo.templatetags.x_templates_extra,debug_toolbar.templatetags.x_templates_extra 

这是我所做的:

1. created a templatetags directory, at the same level as models.py, views.py, etc 
 
2. created a __init__.py file inside the templatetags directory to ensure the directory is treated as a Python package 
 
3. created a file inside the templatetags directory called x_templates_extra.py 
 
4. added the load tag to the template: {% load x_templates_extra %} 
 
5. added the tag to the template: {{ x_detail.x_details_institution_name|safe|replace:"<br />"|striptags|truncatechars:popover_string_length_20 }} 
 
6. Added the following code to the file x_templates_extra.py: 
 
from django import template 
 
register = template.Library() 
 
def replace(value, arg): 
   """Replaces all values of arg from the given string with a space.""" 
    return value.replace(arg, ' ') 

问题:

文档指出:因此,在模块顶部附近,放置以下内容:

from django import template 
 
register = template.Library() 

我已将导入和注册行放在名为 x_templates_extra.py 的文件中。对吗?

此外,我不确定要在 INSTALLED_APPS 中放入什么才能使负载正常工作。

尝试了很多东西,但我现在正在兜圈子,所以我确实需要帮助。

谢谢。

请您参考如下方法:

终于成功了。

向已安装的应用程序添加正确的应用程序名称是个问题。