d3pd
d3pd

Reputation: 8295

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")

Upvotes: 5

Views: 8951

Answers (1)

davidism
davidism

Reputation: 127180

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>
'''

Upvotes: 7

Related Questions