博客五部曲之一 - 简单博客


1215 浏览 5 years, 4 months

31 自定义模板标签

版权声明: 转载请注明出处 http://www.codingsoho.com/

这一章我们将通过模板标签来实现上面的内容转换功能

首先在posts下面创建文件夹 templatetags, 并创建文件__init__.py
创建文件urlify.py并添加下面代码

from django import template
from urllib import quote_plus

register = template.Library()
@register.filter
def urlify(value):
    return quote_plus(value)

在post_detail.py里使用urlify这个标签,首先通过{% load urlify %}加载这个标签,然后和其他标签一样|urlify实现其功能。

{% load urlify %}
        <a href="[http://v.t.sina.com.cn/share/share.php](http://v.t.sina.com.cn/share/share.php)?title={{{instance.content|truncatechars:80|urlify}}%20&url={{ request.build_absolute_url }}" target="_blank">share on weibo</a>

更多细节查看 https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/