Django HTML截断

Hel*_*nar 3 django django-templates

我正在使用Django 的内置truncatewords_html过滤器,它最后添加"...",相反,我想用链接"查看更多"替换它.

我怎样才能做到这一点?

Ken*_*ane 9

最好编写自己的过滤器.您可以获取truncatewords_html的源代码,并将其用作过滤器的模板.它应该做一些改变才能得到你想要的东西,然后你只需要注册你的模板,并确保你将它加载到你想要使用它的页面上,你应该是好的.

有关详细信息,请参阅此页面 https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

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

您应该能够复制该方法,只需将代码更改为此.

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

您想要"查看更多"链接,这将需要更多代码.我会更改过滤器以接受另一个参数,这是"查看更多"的链接.

然后,不是只是将"看到更多"传递给Truncator,而是传递HTML链接.