在解决这个问题时我遇到了困难。我有一个模板包含在其他模板中,但我无法在包含的模板中呈现任何模板变量。我有一个单独的模板标记文件用于包含的模板。我现在完全不知道如何解决这个问题。
我希望能够在模板中渲染我的模型中的字段值(其中包含图像、简短描述等)。我相当确定我正在以错误的方式处理此问题。
下面是我的代码:
型号:
class AddOnItem(models.Model):
base_product = models.ForeignKey(Product)
base_price = models.DecimalField(max_digits=8, decimal_places=2, default=0.0)
addon_image = models.ImageField(upload_to='uploads/shop/product/images/',
default='uploads/shop/product/images/', help_text='Max width: 450px')
short_description = models.CharField(max_length=255, blank=True)
def __unicode__(self):
return self.base_product.name
模板:
{% load addon_tags %}
{% if items_to_add %}
{% for items in items_to_add %}
<div id="addon-container">
<div id="left-addon" class="addon-container">
<a href=""><img src="#" class="addon-image"></a>
<p class="addon-description">{{items.short_description}}</p>
</div>
</div>
{% endfor %}
{% endif %}
addon_tags.py:
from django import template
from sho.models import AddOnItem
register = template.Library()
@register.inclusion_tag("foo/templates/v/sho/addon.html", takes_context=True)
def add_on_render():
context['items_to_add'] = AddOnItem()
return context
我想我要么做错了很多(我目前的假设),要么错过了一些小细节。我已经为此工作了几天,并反复查看了文档。我只是完全错过了一些东西,这已经成为我的主要障碍。任何帮助将不胜感激。
Django 版本 1.4
编辑: 我最终重写了 View 并取消了模板标签。感谢 Daniel Roseman 和 Odif Yltsaeb 的回复。
最佳答案
1) 从您的帖子中,您将空的新项目添加到 add_on_render templateag 的上下文中。
2)我在你的帖子中看不到你在哪里使用 {% add_on_render %} 模板标签。您已经创建了 templattag,但似乎没有在任何地方使用它。
有点难以理解您到底想做什么或为什么需要 templatetag。
如果您想显示模型字段值,则不需要 templateag,并且您在本文的"template"部分中显示的所有内容都可以很好地在您的主模板中,我认为是没有显示在您的帖子中。
如果你想使用 templatetag,那么这个 templatetag 可能应该接收 AddOnItem istance 作为参数,如下所示:
@register.inclusion_tag("foo/templates/v/sho/addon.html", takes_context=True)
def add_on_render(item):
context['items_to_add'] = item
return context
你可以在像这样的模板中使用它:
{% load addon_tags %}
{% if items_to_add %}
{% for items in items_to_add %}
<div id="addon-container">
<div id="left-addon" class="addon-container">
<a href=""><img src="#" class="addon-image"></a>
<p class="addon-description">{% add_on_render items %}</p>
</div>
</div>
{% endfor %}
{% endif %}
和你的 foo/templates/v/sho/addon.html 想要这样的:
{{ items_to_add.short_description }}
但是这样做似乎非常不必要,因为您可以通过使用“主”模板之外已有的模板代码来实现所有这些,而无需 templatag。
关于python - 在 Django 中渲染模板变量时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20963799/