2012-08-23 35 views
1

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' 

疑问

我不能够理解为什么这个自定义过滤器不工作。虽然所有其他预定义的过滤器(如标题)都可以正常工作,但此自定义过滤器根本无法使用自定义模板过滤器不工作

回答

3

根据the documentation

例如,如果您的自定义标签/过滤器在一个名为poll_extras.py,您的应用程序布局可能是这样的:

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

您已经在views.py中定义了您的templatefilter。它应该有:

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

首先,创建yourapp/templatetags/文件夹,yourapp/templatetags/__init__.py空文件。将您的templatetag定义放在yourapp_tags.py文件夹中。


且模板中你可以使用下列内容:

{% load poll_extras %} 

最后,在你的模板,把{%负载yourapp_tags%}启用templatetag 。

+0

没有它的views.py文件中定义的 – Abhimanyu

+0

的权利,所以这是一个双重错误。我认为我的答案更新应该涵盖这一切。感谢您的反馈意见 ! – jpic

+0

现在它说 在/ rprofile/info 上的TemplateSyntaxError'beenthere_tags'不是一个有效的标签库:模板库beenthere.templatetags.beenthere_tags没有名为'register'的变量 – Abhimanyu

相关问题