Django HTML truncation

蓝咒 提交于 2019-12-12 15:51:13

问题


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?


回答1:


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.




回答2:


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>" }}



回答3:


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.



来源:https://stackoverflow.com/questions/8553786/django-html-truncation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!