Django使用心得(四)
本篇主要講解如何在django的模板中自定義tag。
主要內容:
- 自定義tag的步驟
- 帶參數和不帶參數的自定義tag
- 在模板中使用自定義的tag
- 補充說明
1. 自定義tag的步驟
自定義tag主要有以下5步:
1.1 新建django工程 customTags。建立方法參見Django使用心得(一)
1.2 新建文件夾templatetags,好像必須是這個名字。
1.3 在文件夾templatetags中新建一個空文件__init__.py,表明templatetags是個python模塊。
1.4 在此文件夾中新建python文件,并實現自定義的tag。
1.5 在settings.py文件的INSTALLED_APPS中添加此模塊。
1.6 在模板中先load自定義tag所在的模塊,在使用自定義tag。
2. 帶參數和不帶參數的自定義tag
下面實現上面步驟 1.3。在templatetags文件夾中新建文件myTags.py,內容如下:
#!/usr/bin/env python # -*- coding: utf-8 -*-from django import template register = template.Library()def do_tags_without_para( parser, token ):return TagsWithoutPara()def do_tags_with_para( parser, token ):paras = token.split_contents()if len( paras ) != 6:raise template.TemplateSyntaxError("this tag takes exactly five arguments")return TagsWithPara(paras)class TagsWithoutPara( template.Node ):def render( self, context ):context['content'] = "My custom tags without parameters"return ''class TagsWithPara( template.Node ):def __init__( self, paras ):self.paras = parasdef render( self, context ):context['paras_0'] = self.paras[0]context['paras_1'] = self.paras[1]context['paras_2'] = self.paras[2]context['paras_3'] = self.paras[3]context['paras_4'] = self.paras[4]context['paras_5'] = self.paras[5]return ''register.tag('custom_tags_without_para', do_tags_without_para) register.tag('custom_tags_with_para', do_tags_with_para)實現一個自定義tag的方法
- 定義一個tags類并繼承template.Node,其中的render方法有個參數context,里面的內容可以在模板中使用。
- 定義一個方法do_***(),此方法就是返回自定義的tags類。
- 利用方法register.tag(para1, para2)注冊自定義的tag,其中para1即為在模板中使用的tag名稱,para2是上一步定義的方法。
3. 在模板中使用自定義的tag
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>Custom tags</title></head><body>{% load myTags %}<h1>custom tags without parameters</h1>{% custom_tags_without_para %}<p>Content is :</p><h2>{{ content }}</h2><hr /><h1>custom tags with 5 parameters</h1>{% custom_tags_with_para a b c d e %}<p>parameters are :</p><h2>the tag name is : {{ paras_0 }}</h2><h2>{{ paras_1 }}</h2><h2>{{ paras_2 }}</h2><h2>{{ paras_3 }}</h2><h2>{{ paras_4 }}</h2><h2>{{ paras_5 }}</h2></body> </html>4. 補充說明
為了能在模板中使用自定義tag,還需要在settings.py文件的INSTALLED_APPS中添加templatetags所在模塊。
注意,這里是templatetags所在模塊,而不是上面myTags.py所在的模塊。
只要在INSTALLED_APPS中加入'customTags', 即可,我開始做的時候一直是加入'customTags.templatetags',
然后運行時模板始終找不到自定義的tag。
原來django在找自定義tag時會自動在INSTALLED_APPS里的各個模塊后加上.templatetags。
這也是本文開始時【1.2 新建文件夾templatetags,好像必須是這個名字?!康脑?。
我的整個示例工程的結構如下:
D:\Vim\python\django|- customTags| |- __init__.py| |- manage.py| |- settings.py| |- urls.py| |- views.py| || `- templatetags| |- __init__.py| `- myTags.py|`- django-templates`- customTags`- index.html運行后頁面如下:
轉載于:https://www.cnblogs.com/wang_yb/archive/2011/05/12/2044908.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Django使用心得(四)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Titanium Developer
- 下一篇: 再谈querySelector和quer