第五章 定制模板过滤器与标签.md

最后更新于:2022-04-01 21:59:50

{% raw %} 第五章 定制模板过滤器和标签 ------------------------ 本章,我们会学习以下内容: * 遵循模板过滤器和标签的约定 * 创建一个模板过滤器显示已经过去的天数 * 创建一个模板过滤器提取第一个媒体对象 * 创建一个模板过滤器使URL可读 * 创建一个模板标签在模板中载入一个QuerySet * 创建一个模板标签为模板解析内容 * 创建一个模板标签修改request查询参数 ## 简介 如你所知,Django有一个非常庞大的模板系统,特别是模板继承, ## 遵循模板过滤器和标签的约定 Custom template filters and tags can become a total mess if you don't have persistent guidelines to follow. Template filters and tags should serve template editors as much as possible. They should be both handy and flexible. In this recipe, we will look at some conventions that should be used when enhancing the functionality of the Django template system. 滤器和标签时会让你完全不知所措。模板过滤器和标签应该尽可能的服务于模板编辑器,而且它们都应该同时具有操作方便和灵活扩展的特性。在这个做法中,我们会见到一些在增强Django模板系统功能时所用到的几点约定。 ### 如何做 扩张Django模板系统时遵循以下约定: 1. 当在视图,上下文处理器,或者模型方法中,页面更适合逻辑时,不要创建或者使用定制模板过滤器、标签。你的页面是上下文指定时,比如一个对象列表或者一个详细对象视图,载入视图中的对象。如果你需要在每一个页面都显示某些内容,可以创建一个上下文管理器。当你需要获取一个没有关联到模板上下文的对象的某些特性时,要用模型的定制方法而不是使用模板过滤器。 2. 使用 _tags后缀命名模板标签库。当你的app命名不同于模板标签库时,你可以避免模糊的包导入问题。 3. 例如,通过使用如下注释,在最后创建的库中,从标签中分离过滤器: # -*- coding: UTF-8 -*- from django import template register = template.Library() ### FILTERS ### # .. your filters go here .. ### TAGS ### # .. your tags go here.. 4. 通过下面的格式,创建的模板标签就可以被轻松记住: for [app_name.model_name]:使用该格式以使用指定的模型 using [template_name]:使用该格式将一个模板的模板标签输出 limit [count]:使用该格式将结果限制为一个指定的数量 as [context_variable]:使用该结构可以将结构保存到一个在之后多次使用的上下文变量 5. 要尽量避免在模板标签中按位置地定义多个值除非它们都是不解自明的。否则,这会有可能使开发者迷惑。 6. 尽可能的使用更多的可理解的参数。没有引号的字符串应该当作需要解析的上下文变量或者可以提醒你关于模板标签组件的短语。 ## 参见 The Creating a template filter to show how many days have passed recipe The Creating a template filter to extract the first media object recipe The Creating a template filter to humanize URLs recipe The Creating a template tag to include a template if it exists recipe The Creating a template tag to load a QuerySet in a template recipe The Creating a template tag to parse content as a template recipe The Creating a template tag to modify request query parameters recipe” ## 创建一个模板过滤器显示已经过去的天数 Not all people keep track of the date, and when talking about creation or modification dates of cutting-edge information, for many of us, it is more convenient to read the time difference, for example, the blog entry was posted three days ago, the news article was published today, and the user last logged in yesterday. In this recipe, we will create a template filter named days_since that converts dates to humanized time differences. 不是所有的人都持续关注时间,而且在谈论最新日期信息的新建和修改时,对于我们大多数人来说读取时间差是更为合适的一种选择,例如,博客内容在发布于三天之前,新的文章在今天发布了,而用户则是在昨天进行了最后的登陆行为。在这个做法中,我们将新一个称作days_since的可以转换日期到人类可读时间差的模板过滤器。 ## 准备开始 Create the utils app and put it under `INSTALLED_APPS` in the settings, if you haven't done that yet. Then, create a Python package named templatetags inside this app (Python packages are directories with an empty ` __init__.py` file). 创建utils应用并将它放到settings文件中的`INSTALLED_APPS`下,要是你还没有按照我说的去做的话。然后,在这个应用里边创建一个名叫templatetags的Python文件夹(Python包是一个拥有内容为空的`__init__.py`文件)。 ## 我该怎么做 使用下面的内容创建一个utility_tags.py文件: ```python #utils/templatetags/utility_tags.py # -*- coding: UTF-8 -*- from datetime import datetime from django import template from django.utils.translation import ugettext_lazy as _ from django.utils.timezone import now as tz_now register = template.Library() ### FILTERS ### @register.filter def days_since(value): """ Returns number of days between today and value.""" today = tz_now().date() if isinstance(value, datetime.datetime): value = value.date() diff = today - value if diff.days > 1: return _("%s days ago") % diff.days elif diff.days == 1: return _("yesterday") elif diff.days == 0: return _("today") else: # Date is in the future; return formatted date. return value.strftime("%B %d, %Y") ``` ## 工作原理 If you use this filter in a template like the following, it will render something like yesterday or 5 days ago: 假如你在模板中使用了如下所示的过滤器,那么该过滤器会将日期渲染为比如,今天,或者五天前: ```python “{% load utility_tags %} {{ object.created|days_since }} You can apply this filter to the values of the date and datetime types. ``` Each template-tag library has a register where filters and tags are collected. Django filters are functions registered by the `register.filter` decorator. By default, the filter in the template system will be named the same as the function or the other callable object. If you want, you can set a different name for the filter by passing name to the decorator, as follows: 每个模板标签库都有一个收集过滤器和标签的注册器。Django过滤器是通过装饰器`register.filter`注册过的函数。默认,模板系统中的过滤器的名称和函数或者其他可调用对象的名称相同。如下,如果你有需要的话,你可以通过传递名称到装饰器来为过滤器设置一个不同的名称: ```python @register.filter(name="humanized_days_since") def days_since(value): ... ``` The filter itself is quite self-explanatory. At first, the current date is read. If the given value of the filter is of the datetime type, the date is extracted. Then, the difference between today and the extracted value is calculated. Depending on the number of days, different string results are returned. ## 还有更多 This filter is easy to extend to also show the difference in time, such as just now, 7 minutes ago, or 3 hours ago. Just operate the datetime values instead of the date values. ## 参阅 The Creating a template filter to extract the first media object recipe The Creating a template filter to humanize URLs recipe ## 创建一个模板过滤器以提取第一个媒体对象 Imagine that you are developing a blog overview page, and for each post, you want to show images, music, or videos in that page taken from the content. In such a case, you need to extract the ``, ``, and `` tags out of the HTML content of the post. In this recipe, we will see how to do this using regular expressions in the `get_first_media` filter. ## 准备开始吧 We will start with the `utils` app that should be set in `INSTALLED_APPS `in the settings and the `templatetags` package inside this app. ## 如何做 In the `utility_tags.py` file, add the following content: 在`utility_tags.py`文件中,添加以下内容: ```python #utils/templatetags/utility_tags.py # -*- coding: UTF-8 -*- import re from django import template from django.utils.safestring import mark_safe register = template.Library() ### FILTERS ### media_file_regex = re.compile(r"|" r"<(img|embed) [^>]+>") ) @register.filter def get_first_media(content): """ Returns the first image or flash file from the html content """ m = media_file_regex.search(content) media_tag = "" if m: media_tag = m.group() return mark_safe(media_tag) ``` ## 工作原理 While the HTML content in the database is valid, when you put the following code in the template, it will retrieve the ``, ``, or `` tags from the content field of the object, or an empty string if no media is found there: ```python {% load utility_tags %} {{ object.content|get_first_media }} ``` At first, we define the compiled regular expression as `media_file_regex`, then in the filter, we perform a search for that regular expression pattern. By default, the result will show the <, >, and & symbols escaped as `<`, `>`, and `&`; entities. But we use the `mark_safe` function that marks the result as safe HTML ready to be shown in the template without escaping. ## 还有更多 It is very easy to extend this filter to also extract the `|" r"