Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 397
Hellnar Avatar asked Dec 27 '22 09:12

Hellnar


2 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.

like image 126
Ken Cochrane Avatar answered Jan 08 '23 03:01

Ken Cochrane


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>" }}
like image 28
Moz Morris Avatar answered Jan 08 '23 05:01

Moz Morris