This question already has answers here:
Passing HTML to template using Flask/Jinja2
(7 answers)
Closed 4 years ago.
So I want to put an svg file into my page(not as an image, as an xml element) - need it like this so I could dynamically change elements within the page.
and I made a simple code that I thought it'll do:
#app.route('/map_test/')
def test():
svg = render_template('file.svg')
response = make_response(svg)
response.content_type = 'image/svg+xml'
return render_template('test.html', svg=response)
and test.html:
{% block content %}
<section>
{{ svg }}
</section>
{% endblock %}
....which just returned <Response 126181 bytes [200 OK]> instead of svg element...
so... what do I need to do in order to get this to work?
this did the trick:
from flask import Markup
#app.route('/map_test/')
def test():
svg = open('file.svg').read
return render_template('test.html', svg=Markup(svg))
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
img = './static/download.svg'
return render_template('index.html', img=img)
if __name__ == '__main__':
app.run()
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<img src="{{ img }}">
</body>
</html>
put your svg file in dir called static
Related
The following code works perfectly from the .py file but I want to separate the HTML and put it in templates/index.html.
I suppose I have to use the render_template function in Flask to be able to return the same results.
# File dynamic_website.py
from owlready2 import *
onto = get_ontology("bacteria.owl").load()
from flask import Flask, url_for
app = Flask(__name__)
#app.route('/')
def ontology_page():
html = """<html><body>"""
html += """<h2>'%s' ontology</h2>""" % onto.base_iri
html += """<h3>Root classes</h3>"""
for Class in Thing.subclasses():
html += """<p>%s</p>""" % (url_for("class_page", iri = Class.iri), Class.name)
html += """</body></html>"""
return html
I created a folder template and a file index.html. I used return render_template('index.html') but it doesn't work. What arguments do I have to add to the return_template function? "for Class in Thing.subclasses():" have to be in the .html file or .py file? What about the url_for function?
If you could edit the .py code and let me know what should I write exactly in the index.html file to have the same results it would be great.
UPDATE:
What I have done:
Python code
from flask import Flask, render_template
from owlready2 import *
from flask import Flask, url_for
onto = get_ontology("bacteria.owl").load()
app = Flask(__name__)
#app.route("/")
def ontology_page():
for Class in Thing.subclasses():
return render_template('index.html')
Html code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>{{ Class.name }}</h1>
</body>
</html>
You can't return a function multiple times. Whatever is returned, is the value of the function. This tutorial is in JS, but it implies the same concept as python does.
If you want the user to see a list of things on the html, do this. render_template('index.html', things=Thing.Subclasses()) This will give Jinja a list, where it can then for loop.
For html you can do this
{% for s in things %} {{ s }} is something {% endfor %}. Do anything you want with the s though, s is one subclass from the list.
So I have this dummy json file which has id, title, subtitle, and post, using npoint here's the link to json data: https://api.npoint.io/5abcca6f4e39b4955965, and what i'm trying to do was display the title and subtitle of the 3 posts from the dummy json file. I used jinja multi line to loop through the post within the html. But I keep getting an error, I've tried printing out the data to console and it worked just fine.
here's my server.py :
from flask import Flask
from flask import render_template #grabs your html page to render
import random
import requests
from datetime import datetime
app = Flask(__name__)
#app.route('/')
def hello():
return "<h1> Welcome! </h1>"
#app.route('/blog')
def blog():
blog_url = "https://api.npoint.io/5abcca6f4e39b4955965"
response = requests.get(url=blog_url)
data = response.json()
return render_template("blog.html", posts=data)
if __name__ == "__main__":
app.run(debug=True)
and heres my blog.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Blog</title>
</head>
<body>
{% for blog_posts in posts: %}
<h1>{{ blog_posts["title] }}</h1>
<h2>{{ blog_posts["subtitle"] }}</h2>
{% endfor %}
</body>
</html>
Error :
File "C:\Users\Vimalan\PycharmProjects\100CODECHALLENGE\Webdev\Blog\templates\blog.html", line 10, in template
<h2>{{ blog_posts["subtitle"] }}</h2>
jinja2.exceptions.TemplateSyntaxError: expected token ',', got 'subtitle'
any suggestions?
Am very much new to Flask & Python, so want to understand/clear my concepts. I have a webpage which i created using flask & wtforms. Html page is very simple having just single field & a submit button. I want to call a python script (test.py) itself or python function(pythonfunction()) when submit button is clicked. Also Is there a way from the webpage,whatever i enter , i can pass as an attribute to that python script (test.py)? help appreciated
**app.py**
from flask import Flask , render_template,flash,redirect,url_for,session,logging,request
from wtforms import Form,StringField,TextAreaField,PasswordField,validators,SelectField,TextAreaField
from wtforms.widgets import TextArea
import subprocess
import test
app=Flask(__name__)
#app.route ('/')
def index():
return render_template('home.html')
class testpython(Form):
testenter=StringField('Enter something')
#app.route ('/testpage',methods=['GET','POST'])
def testpage():
form=testpython(request.form)
return render_template('testpage.html',form=form,python=testfunc(testenter))
if __name__ == '__main__':
app.run(debug=True)
**test.py**
def pythonfunctiontest (self):
print data #<something i can print here from that text field in webpage>
return "all good"
**testpage.html**
{% extends 'sec_layout.html'%}
{% block body %}
{% from "includes/_formhelpers.html" import render_field %}
<form method="POST" action ="">
<div class="form-group">
{{render_field(form.testenter,cols="1", rows="5",class_="form-control")}}
</div>
<div class="input-bar-item input-bar-item-btn">
<button class="btn btn-info">Submit</button>
</div>
</form>
{% endif %}
{% endblock%}
sec_layout.html
<!DOCTYPE <!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>MY PAGE-TEST</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
{% include 'includes/_navbar.html' %}
<div class= "container">
{% block body %}{% endblock%}
</div>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" </script>
</body>
</html>
The question is very general so I will try and give you a steer and perhaps you might revisit this question later with a little more clarity.
Flask asks a server and renders webpages. I.e. it executes some code on the server and passes it to the client web browser. The client web browser can then execute client side code (i.e. Javascript) as the user is browsing and can pass data back to the server using submit forms (to different Flask routes) or via JavaScript AJAX requests (again to other Flask routes). So if you want to execute python script based on some input you will need a separate route.
Here is a simple example of an index page and a second route that will execute something else:
#app.route('/index')
def index():
""" very basic template render """
return render_template('index.html')
#app.route('/data-submit', methods=["POST"])
def calc():
data = request.form.information.data
# do something with data..
x = data + data
return render_template('new_page.html', x)
========= (index.html)
<html>
<body>
<form action="{{ url_for('app.calc') }}" method="POST">
<input name="information" type='text'>
<button name="submit">
</form>
</body>
</html>
Wrap whatever temp.py is doing in a function.
Place it in the same directory as flask.py. Call import temp in flask.py, then use temp.myfunction().
This question already has answers here:
How to serve static files in Flask
(24 answers)
Link to Flask static files with url_for
(2 answers)
Closed 5 years ago.
I am trying to pass a filename of an image and render it on a template,
Although I am passing the actual name through it does not display on the page
#app.route('/', methods=['GET','POST'])
#app.route('/start', methods=['GET','POST'])
def start():
person_to_show = 'tim'
profilepic_filename = os.path.join(people_dir, person_to_show, "img.jpg")
return render_template('start.html',profilepic_filename =profilepic_filename )
For example: profilepic_filename = /data/tim/img.jpg
I have tried
{{profilepic_filename}}
<img src="{{ url_for('data', filename='tim/img.jpg') }}"></img>
And I have also tried
<img src="{{profilepic_filename}}"></img>
Neither of which worked
I have created people_photo in static folder and placed an image named shovon.jpg. From the application.py I passed the image as variable to template and showed it using img tag in the template.
In application.py:
from flask import Flask, render_template
import os
PEOPLE_FOLDER = os.path.join('static', 'people_photo')
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = PEOPLE_FOLDER
#app.route('/')
#app.route('/index')
def show_index():
full_filename = os.path.join(app.config['UPLOAD_FOLDER'], 'shovon.jpg')
return render_template("index.html", user_image = full_filename)
In index.html:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<img src="{{ user_image }}" alt="User Image">
</body>
</html>
Output:
This question already has an answer here:
Call python function using HTML
(1 answer)
Closed 8 years ago.
I have a python script (display_names.py) that displays the list of names in the json file
def search():
with open('business_ten.json') as f:
data=f.read()
jsondata=json.loads(data)
for row in jsondata['rows']:
a=str(row['name'])
yield a
print list(search())
I am trying to call this function in my html file(crawl.html) using flask.
{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>Welcome to the Rating app<h2>
<h3>This is the home page for the Rating app<h3>
</div>
<body>
<p>{{ myfucntion}}</p>
</body>
{% endblock %}
My routes file is as follows:
from flask import Flask,render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
#app.route('/crawl')
def crawl():
return render_template('crawl.html' , myfucntion=search)
if __name__ == '__main__':
app.run()
This doesnt work and it always gives an error on the html page
please help
I believe you need to execute the function when calling it. In python, to execute a function, you use parentheses, so try:
{{ myfucntion() }}
Edit: I see you typoed them both, so that was not an issue. My apologies.