[英]Unique HTML element IDs for each model with Django
我已經使用復選框輸入在頁面上顯示了django模型,該復選框上面有一個標簽,如下所示:
{% if recipes_list %}
<table>
{% for r in recipes_list %}
<tr>
<td>
<section class="ac-container">
<div>
<input id="ac-1" type="checkbox" />
<label for="ac-1">{{r.name}}</label>
<article class="ac-small">
<ul>
{% for i in r.ingredient_list%}
<li>{{i.part}}, {{i.amount}}</li>
{% endfor %}
</ul>
</article>
</div>
</section>
</td>
</tr>
{% endfor %}
</table>
當我單擊recipes_list
中每個條目的標簽時,它顯然總是打開第一個條目的文章。 在過去的幾天里,我一直在尋找解決方案,以解決如何在html中為每個模型條目提供唯一ID的問題,但是我找不到適合這種情況的任何方法。 我已經嘗試過表格,模型表格,各種javascript和php。 我怎樣才能做到這一點?
您可以使用forloop.counter實現此目的:
{% if recipes_list %}
<table>
{% for r in recipes_list %}
<tr>
<td>
<section class="ac-container">
<div>
<input id="ac-{{forloop.counter}}" type="checkbox" />
<label for="ac-{{forloop.counter}}">{{r.name}}</label>
<article id="article-{{forloop.counter}}" class="ac-small">
<ul>
{% for i in r.ingredient_list%}
<li>{{i.part}}, {{i.amount}}</li>
{% endfor %}
</ul>
</article>
</div>
</section>
</td>
</tr>
{% endfor %}
</table>
希望這可以幫助!
它簡單易用的對象主鍵作為id是因為它是唯一的(除非您有來自另一個模型的另一個循環):
{% for r in recipes_list %}
<input id="ac-{{ r.id }}" type="checkbox" />
{% endfor %}
或使用forloop.counter
:
{% for r in recipes_list %}
<input id="ac-{{ forloop.counter }}" type="checkbox" />
{% endfor %}
您可以編寫一個獲取型號名稱的過濾器
from django import template
register = template.Library()
@register.filter(name='class_name')
def class_name(obj):
return obj.__class__.__name__
並在模板中:
在模板中,您想要ID /類名的位置:
<article id={{obj|class_name}}>
{# further code #}
</article>
class MyModel(models.Model):
#fields
def class_name(self):
return "%s"%self.__class__.__name__ #returns the model instance name
如果要返回實例名稱:
from django.template.defaultfilters import slugify
class MyModel(models.Model):
def class_name(self):
return "%s"%(slugify(self.name)) #or whatever field has the specific instance name
並在模板中:
{{obj.class_name}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.