django template string - replace line break with line space - django

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?

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.

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.

Related

How can I truncate a text and use the second part of the text?

I'm researching for a little problem.
I get on my Django template a text. The point is truncate that text, and add the second part of the text in other tag.
I read about:
{{ value|truncatechars_html:x }}
It can works, but I can't use the second part of truncated text.
If someone has an idea...Thanks!!!!
Use slice - see docs here. Strings in python are also lists of characters, so you can do something like this:
First part is {{ value|slice:":x" }}
Second part is {{ value|slice:"x+1:" }}
HOWEVER, if you need to keep some html code, slice won't do it. For that, you will need to write your own custom tag (you can look into the code from truncate chars) which returns two values - one for each part of your string.
Assuming your filter returns something like this:
def your_truncate_filter(value, arg):
... # your code for splitting
data = {}
data['first'] = "....." # first part of string with html tags !!!
data['second'] = "....." # second part of string
return data
you can access it in your template like this:
{% with parts=value|your_truncate_filter:x %}
{{ parts.first }}
{{ parts.second }}
{% endwith %}

Make the first letter uppercase inside a django template

I am pulling a name from a database which is stored as myname. How do I display this inside a Django template as Myname, with the first letter being in uppercase.
Using Django built-in template filter called title
{{ "myname"|title }}
I know it's a bit late, but you can use capfirst:
{{ "waiting for action"|capfirst }}
This will result into "Waiting for action"
This solution also works if you have multiple words (for example all caps):
{{ "ALL CAPS SENTENCE"|lower|capfirst }}
This will output "All caps sentence".
The title filter works fine, but if you have a many-words string like: "some random text", the result is going to be "Some Random Text". If what you really want is to uppercase only the first letter of the whole string, you should create your own custom filter.
You could create a filter like this (follow the instructions on how to create a custom template filter from this doc - it's quite simple):
# yourapp/templatetags/my_filters.py
from django import template
register = template.Library()
#register.filter()
def upfirstletter(value):
first = value[0] if len(value) > 0 else ''
remaining = value[1:] if len(value) > 1 else ''
return first.upper() + remaining
Then, you should load the my_filters file at your template, and use the filter defined there:
{% load my_filters %}
...
{{ myname|upfirstletter }}
It worked for me in template variable.
{{ user.username|title }}
If the user is "al hasib" then the it will return "Al Hasib"
or
{{ user.username|capfirst }}
If user is 'hasib' then the last one will return "Hasib"
Both look something like same but there's some differences.
use
{{"myname"|title}}
this will make the fist letter of each word capital
Just use {{myname | capfirst}}
In Django the template filter capfirst capatialize the first letter of a given string.

Django templates - split string to array

I have a model field, which stores a list of URLs (yeah, I know, that's wrong way) as url1\nurl2\nurl3<...>. I need to split the field into an array in my template, so I created the custom filter:
#register.filter(name='split')
def split(value, arg):
return value.split(arg)
I use it this way:
{% with game.screenshots|split:"\n" as screens %}
{% for screen in screens %}
{{ screen }}<br>
{% endfor %}
{% endwith %}
but as I can see, split doesn't want to work: I get output like url1 url2 url3 (with linebreaks if I look at the source). Why?
Django intentionally leaves out many types of templatetags to discourage you from doing too much processing in the template. (Unfortunately, people usually just add these types of templatetags themselves.)
This is a perfect example of something that should be in your model not your template.
class Game(models.Model):
...
def screenshots_as_list(self):
return self.screenshots.split('\n')
Then, in your template, you just do:
{% for screen in game.screenshots_as_list %}
{{ screen }}<br>
{% endfor %}
Much more clear and much easier to work with.
Functionality already exists with linkebreaksbr:
{{ value|linebreaksbr }}
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#linebreaksbr
Hm, I have partly solved this problem. I changed my filter to:
#register.filter(name='split')
def split(value, arg):
return value.split('\n')
Why it didn't work with the original code?
I wanted to split a list of words to get a word count, and it turns out there is a filter for that:
{{ value|wordcount }}
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#wordcount
Apart from whether your original solution was the right approach, I guess the original code did not work because the meaning of the \n is not the same in Python code as it is in HTML: In Python code it means the escaped newline character, in HTML it is just the two separate characters \ and n.
So passing as input parameter \n from the HTML template to the Python code is equivalent to splitting on the Python string \\n: a literal \ followed by a n.

django-sorting: Localization is not working

I am using django soring application:
https://github.com/directeur/django-sorting
I just wonder if there is a way to make local names for sorting filters...
E.g. I am trying to localize following:
<th>{% anchor total Rating %}</th>
And using standard django trick
<th>{% anchor total _("Rating") %}</th>
is not helping... Don't know what to do...
you should use the trans template tag from within templates..
https://docs.djangoproject.com/en/dev/topics/i18n/internationalization/#trans-template-tag
UPDATE
If you want the title to be translated, you'll just need to modify the anchor template tag code of django-sorting, for example, looking at the source here:
https://github.com/directeur/django-sorting/blob/master/django_sorting/templatetags/sorting_tags.py
Inside anchor you could modify it, for example, by adding the ugettext function as "_()" when the title is passed to the SortAnchorNode class:
return SortAnchorNode(bits[1].strip(), _(title.strip()))
Or you can choose another place to fire the translation, this is just for demonstration but it should work
that will translate the title you specify in your tag:
{% anchor total "Result" %} //{% anchor field title %}
You need to be sure to have the words you'll pass translated in your dictionaries..

Using string literals as parameters to template tags in Django templates

One of the things I find myself doing often is passing string literals as parameters to template tags or functions; for instance:
{% url my-url 'my_param' %}
Unfortunately, the django template engine doesn't let you do this. So I find myself doing this a lot in my view code:
my_context_dict['MY_PARAM'] = 'my_param'
and then in my view code:
{% url my-url MY_PARAM %}
Or creating a series of URL mappings, which I personally try to avoid.
Is it possible to use a string literal in Django templates? Or possibly a more elegant solution? I haven't seen anything on here or in the documentation.
This feels wrong but is right.
text
The nested ""'s don't seem like they should work. They do. The Django {% %} material is simply pulled out of the HTML without regard for surrounding context. So the "duplicated" "'s aren't really duplicated at all.
Use double quotes instead of single quotes:
{% url my_view "my_param" %}
Very wierd - I have a django project that uses single quotes to pass a string value and it functions just fine.
<a href="{% url categories 'vendor' %}"</a>
<a href="{% url categories 'crew' %}"</a>
On further investigation it turns out this has changed in django 1.5. It now requires the quotes even around the url pattern name.