I am just looking into using Jinja2 with a python application I have already written. I may be going about this in the wrong way, but here is what I would like to do.
from jinja2 import Environment, FileSystemLoader
from weasyprint import HTML
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template("really.html")
template_vars = {"title":"TITLE","graph":'total.png'}
html_out = template.render(template_vars)
HTML(string=html_out).write_pdf("report.pdf")
This nearly produces what I want, I get a pdf called report.pdf, but instead of the attached file, it is a string of total.png. This is my first run at using Jinja, so hopefully attaching an image like this is possible. Thanks.
This is the template, not much built, just trying to do this piece at first.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h2>Graph Goes Here</h2>
{{ graph }}
</body>
</html>
I have an answer to my own question, I was simply able to add the image url into the template, without trying to pass it in as a variable.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h2>Graph Goes Here</h2>
<img src="graph.png">
</body>
</html>
Guess I was over complicating it a bit...
Related
I'm confused. I'm trying to run pyscript button example from - https://jeff.glass/post/7-guis-pyscript/ (first example - counter)
This is the HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello, World!</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<p id="counter-target">Some Placeholder Text</p>
<py-button>
def on_click(event):
add_one()
</py-button>
<py-script src="myscript.py"></py-script>
</body>
</html>
This is the PYTHON CODE:
internalCount = 0
target = "counter-target"
PyScript.write(target, str(internalCount), append=False)
def add_one():
global internalCount
internalCount += 1
PyScript.write(target, str(internalCount), append=False)
It's showing me the button (using VSC Live server), but nothing happens once clicking on it... also Visual studio code is showing me this error. I don't understand. I shouldn't import anything, right? Thanks
Define two scripts: myscript.py
def add_one(event):
pyscript.write("output", str(global_vars['internalCounter']), False)
global_vars['internalCounter'] += 1
and globals.py
global_vars = {"internalCounter": 1}
declare both of them inside your html file in py-env section:
<py-env>
paths
./globals.py
./myscript.py
</py-env>
be sure to have identation of 4 spaces (no tab chars).
In html declare two pyscript nodes with src attributes pointing to your scripts:
<py-script src='globals.py'></py-script>
<py-script src='myscript.py'></py-script>
change button node as in html below (use pys-onclick) as well as make a div for output.
Complete index.html looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello, World!</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<py-env>
paths
./globals.py
./myscript.py
</py-env>
</head>
<body>
<py-script src='globals.py'></py-script>
<py-script src='myscript.py'></py-script>
<div id="main">
<p id="counter-target">Some Placeholder Text</p>
<py-button pys-onclick="add_one">
</py-button>
<div id="output">Outputs here</div>
</div>
</body>
</html>
This way you have defined a dictionary (globals.py) where you can manipulate global variables (can define them as you like) within a session. In your myscript.py you can have functions and functionalities that you need for your app. You can in the same manner add more scripts if needed. For it to be working you should declare scripts as paths within py-env section of html and add pyscript node for each of them with src attribute pointing to .py scripts.
As you have py-button defined then your on click event is pys-onclick. I added a div for output too as you can see but it can be done differently too. There should be an id for pyscript.write() function to be operational. Regards...
I have a String variable(name) that contains the name of the song.
(Python)
from pytube import YouTube
yt = YouTube("https://www.youtube.com/watch?v=6BYIKEH0RCQ")
name = yt.title #Contains the title of the song
Here is my HTML code for website to download the mp3 song:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Download</title>
</head>
<body>
<button>Click here </button>
</body>
</html>
With this code, I'd like to use the exact title of song as the name of the file when its been downloaded from the user.
I want to use the name Variable from Python in place of Song_name in HTML code.
Please suggest me any possible way in order to make this work.
You can try try this:
from pytube import YouTube
yt = YouTube("https://www.youtube.com/watch?v=6BYIKEH0RCQ")
name = yt.title
HTML=f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Download</title>
</head>
<body>
<button>Click here </button>
</body>
</html>
"""
with open("test.html","w") as f:
f.write(HTML)
This will put title of song in download attribute. If you want you may put it anywhere. Just don't forget to use f"" and {variable}.
This question already has answers here:
Link to Flask static files with url_for
(2 answers)
Closed 1 year ago.
I am new to web development,and I was building my first website with Flask.When I first runned the website,Bootstrap was not working,after that I went in inspect mode and it gave me some errors.
I tried emptying the cache,but it did not change anything.
The projects folders are arranged like this:
This is the HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/bootstrap.css">
{% if title %}
<title> Project--{{Title}} </title>
{% else %}
<title> Project </title>
{%endif%}
</head>
<body>
<div class="alert alert-primary" role="alert">
Hello
</div>
<script src="js/bootstrap.js"></script>
</body>
</html>
The python code:
from flask import Flask,render_template,url_for
app=Flask(__name__,template_folder='Template')
#app.route("/")
def home():
return render_template('Home.html',title='Home')
if __name__=='__main__':
app.run(debug=True)
How can I fix this issue?
Thanks in advance!
You have to keep js and css folder in a folder named static at same level that of templates folder where you will keep only html files.
You can use href="{{ url_for('static', filename='css/bootstrap.css') }}" for a css file named bootstrap.css which is in css folder in static folder. Same you have to do with us files , src="{{ url_for('static', filename='js/bootstrap.js') }}"
I am learning web development in Python. When I open the HTML I get the Ferrari Fiat Ford, which is what I am expecting but then I click on Ferrari and it opens up the new page as make, model, which is not what I want. I want Ferrari Dino.
Could you help me understand what is the problem?
<!DOCTYPE HTML>
<html lang ="en">
<head>
<meta charset="UTF-8">
<title>Python Response</title>
</head>
<body>
<h1>
Ferrari
<a href = 'get.py?make = Fiat & model = Topolino'>Fiat</a>
<a href = 'get.py?make = Ford & model = Mustang'>Ford</a>
</h1>
</body>
</html>
Python
import cgi
data = cgi.FieldStorage()
make = data.getvalue('make')
model = data.getvalue('model')
print ( 'Content-type:text/html\r\n\r\n' )
print ( '''<!DOCTYPE HTML><html lang = "en">
<head>
<meta charset="UTF-8">
<title>Python Response</title>
</head>
<body>
<h1>, make, model,</h1>
Back
</body>
</html>''' )
A variable cannot be a string.
import cgi
data = cgi.FieldStorage()
make = data.getvalue('make')
model = data.getvalue('model')
print ( 'Content-type:text/html\r\n\r\n' )
print ( '''<!DOCTYPE HTML><html lang = "en">
<head>
<meta charset="UTF-8">
<title>Python Response</title>
</head>
<body>
<h1>, ''' + make + ', ' + model + ''',</h1>
Back
</body>
</html>''' )
After testing this out, the HTML is responding as anticipated.
My recommendation goes along lines of this question here: How to pass python variable to html variable?
In summary, you could do this in a better way by writing a function and returning the html. Also, once you've written the python function, rather than have the:
<h1>, make, model,</h1>
You could use a substitution in your python function like so:
"<h1>, %s, %s,</h1>" % (make, model)
Which would be located in the same python file as the two of these variables.
Your template outputs this:
<h1>, make, model,</h1>
And that's all it ever will output. You can instead change it a little and then use the format method to insert values into it.
html = '''<!DOCTYPE HTML><html lang = "en">
<head>
<meta charset="UTF-8">
<title>Python Response</title>
</head>
<body>
<h1>, {make}, {model},</h1>
Back
</body>
</html>'''
print html.format(make=make, model=model)
The values in curlybraces, {make} and {model}, are named tokens inside the string. When you use format() on the string called html, you replace those tokens. In this case, I referenced them directly by name.
ok guys so I have a template.html file like so:
<h1>Hello wolrd</h1>
<div>This is me</div>
And I want to append that to my index file before the closing body tag. Just like so:
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<script type="text/ng-template" id="templates/template.html">
<h1>Hello wolrd</h1>
<div>This is me</div>
</script>
</body>
</html>
I've so far gotten to read the file and append to the end of it but I have yet to add the script tags to the file that I am reading and append to the correct spot of my file. This is what I currently have:
#!/usr/bin/env python
import fileinput
to_readfile=open('index.html', "r")
try:
reading_file=to_readfile.read()
writefile=open('index2.html','a')
try:
writefile.write("\n")
writefile.write(reading_file)
finally:
writefile.close()
finally:
to_readfile.close()
Any help would be much appreciated. Thank you!
The simplest approach would be to add a placeholder in the layout template and then when processing the layout search for the placeholder and replace it with the contents of the other template.
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<script type="text/ng-template" id="templates/template.html">
{{content}}
</script>
</body>
</html>
...
..
.
layout = open('layout.html', "r")
layout_contents = layout.read()
partial=open('partial_file.html','r')
result = layout_contents.replace("{{content}}", partial)
writefile = open("file_to_write.html", "w")
writefile.write("\n")
writefile.write(result)
.
..
....
You can also work on a much more extensive solution such as the ones used by jinja http://jinja.pocoo.org/docs/templates/#template-inheritance.