Fer*_*ves 3 django django-templates
我正在尝试创建自己的模板标签.我是怎么做到的:
文件夹结构:
my_app/
__init__.py
models.py
views.py
my_app/
templates/
show.html
templatetags/
__init__.py
depos.py
Run Code Online (Sandbox Code Playgroud)
depos.py:
# coding: utf-8
from django import template
from core.models import Depos
register = template.Library()
@register.inclusion_tag('show.html')
def show_dep():
dep = Depos.objects.all().order_by('?')[0]
return dep
Run Code Online (Sandbox Code Playgroud)
show.html:
<div id="user_testimonial">
<blockquote>
<p>{{ dep.dep }}</p>
<cite>{{ dep.name }}, {{ dep.from }}</cite>
</blockquote>
</div>
Run Code Online (Sandbox Code Playgroud)
在我的模板中:
{% load depos %}
{% show_dep %}
Run Code Online (Sandbox Code Playgroud)
但我有这个错误:
TypeError at /cadastro
'Depos' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)
您需要将包含标记中的字典对象传递给包含标记模板.它在文档中提到:
首先,定义接受参数的函数并为结果生成数据字典.这里重点是我们只需要返回字典,而不是更复杂的字典.
所以尝试:
@register.inclusion_tag('show.html')
def show_dep():
return {
'dep' : Depos.objects.all().order_by('?')[0]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
978 次 |
| 最近记录: |