I'm scraping some content and trying to display on html page but it display nothing when i try to run jinja loop for dictionary i sent from python file, it runs every variable separately but not running loop on dictionary
Python dictionary i'm trying to display
dictionary = dict(
[('page_title', url), ('title', title), ('anchor', anchor),
('images', images)])
Html code with jinja tags
<div id="dictionary">
{% for items in dictionary %}
<div class="card" style="width: 18rem;">
<img src="{{ items.images }}" class="card-img-top" alt="{{ items.title }}">
<div class="card-body">
<a href="{{ items.anchor }}" class="btn btn-primary"><h5 class="card-title">{{ items.title }}</h5></a>
</div>
</div>
{% endfor %}
2 Answers 2
No any for loop is needed. Directly, you can use dictionary data
<div class="card" style="width: 18rem;">
<img src="{{ dictionary.images }}" class="card-img-top" alt="{{ dictionary.title }}">
<div class="card-body">
<a href="{{ dictionary.anchor }}" class="btn btn-primary"><h5 class="card-title">{{ dictionary.title }}</h5></a>
</div>
</div>
answered Jan 24, 2022 at 17:30
Harsha Biyani
7,28810 gold badges42 silver badges64 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Abdul Subhan
tried but not working
Harsha Biyani
What is the error?
You can create custom template tag like this:
templatetags/tags.py
from django.template.defaulttags import register
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
your_html.html:
<div id="dictionary">
<div class="card" style="width: 18rem;">
<img src="{{ dictionary|get_item:'images' }}" class="card-img-top" alt="{{ dictionary|get_item:'title' }}">
<div class="card-body">
<a href="{{ dictionary|get_item:'anchor' }}" class="btn btn-primary"><h5 class="card-title">{{ dictionary|get_item:'title' }}</h5></a>
</div>
</div>
answered Jan 24, 2022 at 17:46
Ahtisham
10.3k6 gold badges49 silver badges62 bronze badges
10 Comments
Ahtisham
@AbdulSubhan did tried mine ?
Abdul Subhan
its now giving this error : Exception Value: 'str' object has no attribute 'get' Exception Location: /Users/aaa/gsmarena/gsmApp/templatetags/tags.py, line 7, in get_item
Ahtisham
How are you returning
dictionary from your view ?Abdul Subhan
dictionary = dict( [('page_title', url), ('title', title), ('anchor', anchor), ('images', images)]) return render(request, 'searchresult.html', dictionary)
Abdul Subhan
error occurring in tags.py you asked me to create
|
default
dictionary= {'page_title': url,"title":title......}