【问题标题】:Custom template filter not working自定义模板过滤器不起作用
【发布时间】:2012-08-19 06:33:06
【问题描述】:

views.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'

怀疑

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

【问题讨论】:

    标签: python django django-templates django-template-filters


    【解决方案1】:

    根据the documentation

    例如,如果您的自定义标签/过滤器位于名为 poll_extras.py 的文件中,您的应用布局可能如下所示:

    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 中。


    在您的模板中,您将使用以下内容:

    {% load poll_extras %}
    

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

    【讨论】:

    • 是的,所以这是一个双重错误。我认为我的答案更新应该涵盖所有内容。感谢您的反馈!
    • 现在它说 /rprofile/info 'beenthere_tags' 处的 TemplateSyntaxError 不是有效的标签库:模板库 benthere.templatetags.beenthere_tags 没有名为 'register' 的变量
    • 如果没有名为“register”的变量,那么你没有复制这个: from django import template; register = template.Library()
    猜你喜欢
    • 2011-03-29
    • 1970-01-01
    • 2017-08-16
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    相关资源
    最近更新 更多