Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django template string - replace line break with line space

I have a string in my django1.4 template that I want to replace the line breaks with a whitespace. I only want to replace the line breaks with a single white space in the template string.

So far all my searces on django docs, Google and SO have not given me an answer.

Here is my string in my template:

{{ education_detail.education_details_institution_name|safe|truncatechars:20|striptags }}

When I have the following string saved:

University
Bachelor of Something
2008 - 2010

The string in the django template is rendered as:

UniversityB... 

I want to replace the line break with a space between the yB like so:

University B...

How would I do this?

like image 968
user1261774 Avatar asked Oct 11 '25 18:10

user1261774


2 Answers

Here is the custom filter code that I finally got operational:

from django import template

register = template.Library()

@register.filter(name='replace_linebr')
def replace_linebr(value):
    """Replaces all values of line break from the given string with a line space."""
    return value.replace("<br />", ' ')

Here is the call on the template:

{{ education_detail.education_details_institution_name|replace_linebr }}

I hope that this will help somebody else.

like image 71
user1261774 Avatar answered Oct 14 '25 16:10

user1261774


You can rely on built-in truncatechars filter's behavior to replace newlines with spaces. All you need is to pass a length of the string as an argument, so that you would not see your string shortened:

{% with value|length as length %}
    {{ value|truncatechars:length }}
{% endwith %}

This is a bit hacky, but uses only built-in filters.

You can always write a custom filter if you need this kind of functionality to be reusable.

like image 25
alecxe Avatar answered Oct 14 '25 16:10

alecxe