As per my personal interest, I tried a lot for adding CSS & JS files in my basic form without using Flask & Django. How can I do this?
1 Answer
For that, you need to output your CSS and JS file directly to the HTML file. For example, if you have the folder structure as follows:
| Root App |__ assets | |__ css | |_______style.css | |__ Js | |_______ myjs.js |__ bin | |__app.py | |__ templates |___________maintemplate.html |___________demoform.html
You can create a route to output the file by reading it, Please check following code
in your app.py file
import web
import os
routs = (
'/','index',
'/staticFiles','loadStatic'
)
app = web.application(routs, globals())
render = web.template.render('templates/',base="maintemplate")
class index(object):
def GET(self):
return render.demoform()
class loadStatic(object):
def GET(self):
form = web.input(fileName='',filePath='')
fileName=form.file
filePath=form.folder
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = ("../assets/%s/%s" % (filePath,fileName))
abs_file_path = os.path.join(script_dir, rel_path)
temp = open(abs_file_path,'r').read()
return temp
In your maintemplate.html
$def with (content)
<html>
<head>
<title> SAMPLE CODE </title>
<link rel="stylesheet" href="staticFiles?file=style.css&folder=css" />
<script src="staticFiles?file=myjs.js&folder=js"></script>
</head>
<body>
$:content
</body>
</html>
How It Works In app.py, like all CDN CSS/JS links, we are reading the file and returning output to the browser as a HTTP request.