我正在尝试创建自己的模板标签。我是如何做到这一点的:
文件夹结构:
my_app/
__init__.py
models.py
views.py
my_app/
templates/
show.html
templatetags/
__init__.py
depos.py
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
show.html:
<div id="user_testimonial">
<blockquote>
<p>{{ dep.dep }}</p>
<cite>{{ dep.name }}, {{ dep.from }}</cite>
</blockquote>
</div>
在我的模板中:
{% load depos %}
{% show_dep %}
但是我遇到了这个错误:
TypeError at /cadastro
'Depos' object does not support item assignment
最佳答案
您需要将字典对象从包含标记传递到包含标记模板。 It's mentioned in the docs :
First, define the function that takes the argument and produces a dictionary of data for the result. The important point here is we only need to return a dictionary, not anything more complex.
所以尝试一下:
@register.inclusion_tag('show.html')
def show_dep():
return {
'dep' : Depos.objects.all().order_by('?')[0]
}
关于django - 使用自定义模板标签时出错 - 对象不支持项目分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15774760/