Search code examples
pythonhtmlvariablesflaskwebserver

Is it possible to transfer data from Python to HTML template/Website (Using Flask)


I am a noob to this topic and this is my first question here. I want to ask if it is possible to upload a changing variable from python to an HTML textbox/paragraph/forms? I've seen several methods but can't figure out a one which work. I'm using Python 3.4 on my raspberry PI 2 from which I will be also hosting a web server using flask. I would preferabbly use flask too for this task too but anyways if it's not possible I can use any other methods as soon as they are easier.

Thanks in Advance !


Solution

  • The question is quite confusing though, but from what i understood you can do it like this

    in python file:

        from flask import Flask,render_template
        app = Flask(__name__)
        @app.route('/')
        def index():
            name='stackoverflow'
            return render_template('index.html', name=name)
    

    and in index.html file:

        <!DOCTYPE html>
        <html lang="en">
        <head>
        <script>
            var name = {{ name|safe }}
        </script>
        <h2> this is passed from python {{ name }} </h2>
        </html>
    

    NOTE: When you use render_template(), the HTML file you mention inside should be in ./templates/ in our case it should be ./templates/index.html