0

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
  • 1
    change your data structure to dictionary= {'page_title': url,"title":title......} Commented Jan 24, 2022 at 17:20
  • already tried , not working Commented Jan 24, 2022 at 19:48

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

tried but not working
What is the error?
1

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

10 Comments

@AbdulSubhan did tried mine ?
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
How are you returning dictionary from your view ?
dictionary = dict( [('page_title', url), ('title', title), ('anchor', anchor), ('images', images)]) return render(request, 'searchresult.html', dictionary)
error occurring in tags.py you asked me to create
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.