Python

champak
₹2,000.00 ₹300.00
The Python Programming Language at Champak's World
  • 22 students
  • 41 lessons
  • 0 quizzes
  • 10 week duration

Python

Sending a Dictionary to a HTML Template and displaying it using Flask.

This post shows explains sending a dictionary to a HTML template from a Python Server and the data is displayed by running a loop.

Python Code for a single  object


from flask import Flask,render_template,request
app=Flask(__name__)

class Product:
def __init__(self,productname,productquantity,productprice):
self.productname=productname
self.productquantity=productquantity
self.productprice=productprice
def __str__(self):
return "Name = {0}, quantity={1}, Price = {2}".format(self.productname,self.productquantity,self.productprice)

d={1:Product("Pepsi",10,15)}

@app.route("/")

def index():
p1=d.get(1)
return render_template("products.html",name1=p1.productname,quantity1=p1.productquantity,price1=p1.productprice)
if __name__ == "__main__":
app.run(host="localhost", port=int("777"))

Template


<!DOCTYPE html>

<html>
<head>
<title>Products</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>
<body>

<div>
<center>
<table width="100%" border="1">
<tr><td>Name</td><td>Quantity</td><td>Price</td></tr>
<tr><td>{{name1}}</td><td>{{quantity1}}</td><td>{{price1}}</td></tr>
</table>
</center>

</div>
</body>
</html>


Sending a Dictionary to a Template.

</pre>
from flask import Flask,render_template

#app = Flask(__name__)
app = Flask(__name__, static_url_path='/static')
d={2:"Mumbai",1:"Jaipur",3:"Varanasi"}

@app.route("/")

def index():

return render_template('dict.html',dict=d)

if __name__ == "__main__":
#print(__name__)
app.run(host="localhost", port=int("777"))
#app.run()
<pre>

Template

</pre>
<!DOCTYPE html>

<html>
<head>
<title>Products</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>
<body>

<div>
<center>
{{dict}}
</center>

{% for key, value in dict.items() %}
<h1>Key: {{key}}</h1>
<h2>Value: {{value}}</h2>
{% endfor %}

{% for key in dict.keys()%}
{% set value=dict.get(key)%}
<h1>Key: {{key}}</h1>
<h2>Value: {{dict.get(key)}} {{value}}</h2>
{% endfor %}

</div>
</body>
</html>
<pre>

Combine these two and make a template that displays a dictionary of Product objects.

end

Leave a Reply

Your email address will not be published. Required fields are marked *