Tuesday, August 21, 2018

How to use render_template in Flask

Why template is needed?

Let's say we need to a number of dynamic html page. The page need to be changed based on data from outside. Without template, we need to make a static HTML page in manual way. "template" gives an easy way to replace page's content in a very simple way. it feels like a mail merge feature in a word processor.
As we want to make a dynamic page, we need to use this feature "template"

(I am following this Flask tutorial)

This instruction shows how to deal with template, url_for in Flask.

How to use "template"?

import class

in order to use "template", firstly we need to import a class named "render_template" in python file.


from flask import Flask, render_template

preparing a HTML file in "templates" folder

I prepared "hello.html" inside of templates folder.

templates/hello.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>This is hello world</h1>
  </body>
</html>


code it (test.py)

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
@app.route("/hello")
def hello():
    return render_template("hello.html")

if __name__ == "__main__":
    app.run(debug=True)


result 


Sending Data 


from flask import Flask, render_template
app = Flask(__name__)

varForPython = ["welcome", "to", "my", "channel!"]

@app.route("/")
@app.route("/hello")
def hello():
    return render_template("hello.html", varForHtml = varForPython)

if __name__ == "__main__":
    app.run(debug=True)

Receiving Data and Using it in the HTML file



<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    
    {% for line in varForHtml%}
    <h1> {{ line.name }} </h1>
    <p> {{ line.title }}</p>
    <p>{{ line.date }}</p>
    {% endfor %}

  </body>
</html>

No comments:

Post a Comment

URDF Link origin test