Fred Collins
Fred Collins

Reputation: 5010

Django and wrap lines problem

I've a problem from many years.

The problem is a long text not separated by white spaces in a div. No wrap is applied and it breaks all layout.

How can I fix in django in a good way?

This is what I see:

enter image description here

Upvotes: 5

Views: 9856

Answers (3)

msbrogli
msbrogli

Reputation: 493

I don't know if it helps, but an approach could be creating a new filter based on truncatewords filter. https://docs.djangoproject.com/en/dev/ref/templates/builtins/#truncatewords

Code looks very simple:

def truncate_filter(value, maxlen):
    if len(value) <= maxlen:
        return value
    return value[:maxlen-2] + '..'

Another ideia is using: {{ username|stringformat:".10s" }} to truncate in 10 characters. https://docs.djangoproject.com/en/dev/ref/templates/builtins/#stringformat

Upvotes: 1

Jim Bob
Jim Bob

Reputation: 459

This was bugging me as the built-in word-wrap template tag should have just worked. Instead use this...

{{ value|wordwrap:50|linebreaksbr }}

or

{{ value|wordwrap:50|linebreaks }}

depending if you want <br> or <br> and <p> tags

Upvotes: 8

Kirill
Kirill

Reputation: 3454

As I understand the question it is HTML-side problem, not django-side. For HTML solution look How to word wrap text in HTML?. If you still want to wrap text in python code, textwrap.wrap will help you.

Also there is convenient template tag for this: wordwrap. It uses django.utils.text.wrap function which seems more suitable for using in Django projects.

Upvotes: 7

Related Questions