1

I am spitting out some values with a for loop and want to make sure that it only displays X characters. I'm relatively new to Django.

For example:

  <div class="bookauthor">
    by 
    {% for author in book.volumeInfo.authors %}
      {% if not forloop.first %}&amp;{% endif %}
      {{author}}
    {% endfor %} 
  </div>

Would produce a list of book authors, e.g.:

by Lennart Berggren & Jonathan M. Borwein & Peter B. Borwein

and I'd only like 30 characters, since sometimes the list of authors can be long.

I understand that I can use truncatechars (new in Django 1.4) to do this on a single value like {{author|truncatechars:9}}, but I'm wondering if there is an elegant way to apply to the for loop, or the resulting text from the for loop. Please let me know if this isn't clear.

EDIT

truncatechars does not seem to work properly when used in a {% filter %}. All it produces is "...". I'll test some more, could be a bug. truncatewords works well, and I may be more suitable for this situation anyhow.

      <div class="bookauthor">
        by 
        {% filter truncatechars:30 %}
          {% for author in book.volumeInfo.authors %}
          {% if not forloop.first %}&amp;{% endif %}
            {{author}}
          {% endfor %}  
        {% endfilter %}  
     </div>
4

2 回答 2

2

{% filter %}

于 2012-04-24T01:16:03.650 回答
0

使用自定义过滤器(此处的文档)

@register.filter
def queryset_as_list(queryset, attr=None):
    query_list = []
    for param in queryset:
        query_list.append(getattr(param, attr) if attr else str(param))

    return query_list


@register.filter
def str_list(list):
    return ', '.join(list)

我使用过滤器将查询集转换为列表,使用另一个过滤器将列表转换为字符串,最后使用 django 的 truncatechars 过滤器在模板中仅显示 50 个字符,如下所示

{{ book.volumeInfo.authors|queryset_as_list|str_list|truncatechars:50 }}
于 2021-12-27T02:38:26.153 回答