Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate pages with Flask without using separate template files

I'm trying to keep things minimal, so I don't want to create templates, directory structures, etc. I have a simple CSS file available on the web (via RawGit) and I want to use it to style the page generated by a view. How can I render a page without templates?

from flask import Flask
application = Flask(__name__)

# <insert magic here>
# application.get_and_use_my_super_cool_CSS_file(URL)
# <insert magic here>

@application.route("/")
def hello():
    return "hello world"

if __name__ == "__main__":
    application.run(host = "0.0.0.0")
like image 305
d3pd Avatar asked Mar 13 '23 22:03

d3pd


1 Answers

If you don't want to write templates as separate files, you can use render_template_string instead. This is typically not a very useful feature, as it becomes difficult to maintain large templates written as Python strings. Flask's Jinja env also provides some extra help when rendering files it recognizes, such as turning on autoescape for HTML files, so you need to be more careful when rendering from strings directly.

return render_template_string('''<!doctype html>
<html>
    <head>
        <link rel="stylesheet" href="css url"/>
    </head>
    <body>
        <p>Hello, World!</p>
    </body>
</html>
'''
like image 185
davidism Avatar answered May 04 '23 09:05

davidism