Django HTML truncation

I'm using the build-in truncatewords_html filter of Django and it adds "..." in the end, instead, I want to replace this with a link "See More".

How can I achieve this?

Answers


It would be best to write your own filter. You could take the source code for truncatewords_html and use it as a template for your filter. It should take a few changes to get what you want, and then you will just need to register your template and make sure you load it on the page you want to use it on and you should be good.

See this page for more info https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

https://code.djangoproject.com/browser/django/trunk/django/template/defaultfilters.py#L288

You should be able to copy the method and just change the Code to this.

return Truncator(value).words(length, html=True, truncate=' see more')

You want to make 'see more' a link, that will take more code. I would change the filter to accept another param which is the link for 'see more'.

Then instead of just having 'see more' passed to Truncator you would pass the HTML link.


If you wanted to pass a custom link, that could be done like this.

Define your custom filter:

from django import template
from django.utils.safestring import mark_safe
from django.utils.text import truncate_html_words

register = template.Library()

@register.filter
def truncatewords_html_with_link(value, arg):
    """
    Truncates HTML after a certain number of words and concatenates a link

    Argument: String - Number of words to truncate after and the link, 
    separated by a comma
    """    
    arg_list = arg.split(',')
    try:
        length = int(arg_list[0])
    except ValueError:
        return value
    return mark_safe(truncate_html_words(value, length, arg_list[1]))

Call it from your template:

{{ text|truncatewords_html_with_link:"5, <a class=\"read-more\" href=\"/your_url/\">Read More</a>" }}

The relevant code in Django 1.8 reads:

truncate = pgettext(
    'String to return when truncating text',
    '%(truncated_text)s...')

If you are using LOCALE and translation files, place the following into your *.po files:

msgid "String to return when truncating text"
msgstr "Short version: %(truncated_text)s <a class='see-more-link'>see more</a>"

Though, depending on what should happen when you click on the link adding it that way might not be very helpful. You could use another placeholder for it, but then you would have to make sure to replace the placeholder whereever this message string is used.


Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.