gpt4 book ai didi

python - 自定义模板过滤器不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 10:53:22 31 4
gpt4 key购买 nike

View .py

from django import template
register = template.Library()

@register.filter
def truncatesmart(value, limit=80):
"""
Truncates a string after a given number of chars keeping whole words.

Usage:
{{ string|truncatesmart }}
{{ string|truncatesmart:50 }}
"""

try:
limit = int(limit)
# invalid literal for int()
except ValueError:
# Fail silently.
return value

# Make sure it's unicode
value = unicode(value)

# Return the string itself if length is smaller or equal to the limit
if len(value) <= limit:
return value

# Cut the string
value = value[:limit]

# Break into words and remove the last
words = value.split(' ')[:-1]

# Join the words and return
return ' '.join(words) + '...'

html

{% block content %}

<div class="container-fluid">
<div class="container" id="content">
<div class="span3">
<div class="dashboard">
<div class="well smooth-edge2 shadow">
<div class="mini-info">
<div class="username">
<h2 class="text-center">{{rest.name|truncatesmart}}</h2>

{% endblock %}

错误

TemplateSyntaxError at /rprofile/info
Invalid filter: 'truncatesmart'

疑问

我不明白为什么这个自定义过滤器不起作用。虽然所有其他预定义的过滤器(如标题)都在工作,但这个自定义过滤器根本不起作用。

最佳答案

根据 the documentation :

For example, if your custom tags/filters are in a file called poll_extras.py, your app layout might look like this:

polls/
models.py
templatetags/
__init__.py
poll_extras.py
views.py

您已经在 views.py 中定义了模板过滤器。它应该在那里:

yourapp/templatetags/__init__.py
yourapp/templatetags/yourapp_tags.py

首先,创建yourapp/templatetags/ 文件夹和yourapp/templatetags/__init__.py 空文件。将您的模板标签定义放在该文件夹中的 yourapp_tags.py 中。


And in your template you would use the following:

{% load poll_extras %}

最后,在您的模板中,放入 {% load yourapp_tags %} 以启用模板标签。

关于python - 自定义模板过滤器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12096780/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com