Flask – Templating

Create folder templates & put all of html files in there.

layout.html

<html>
<head>
    <title> {% block title %} {% endblock %} </title>
</head>
<body>

  <h1>Layout Template</h1>

  {% block content %}

  {% endblock %}

</body>
</html>

Content.html

{% extends 'layout.html' %}

{% block title %} Title {% endblock %}

{% block content %}

  ... Your Content Here ...

{% endblock %}

Include

(% include "sidebar.html" %)

# di sidebar.html juga bisa passing variable {{ nama }} , berdasarkan function

Conditional / IF

app.py :
name = 'Ava'
location = 'Bali
return render_template('index.html', name=name, location=location, display=True)

index.html :
{% if display %}
  <h1>Hello {{ name }} from {{ location }} !</h1>
{% else %}
  <h1>Hello, World!</h1>
{% endif %}

For Loop

app.py :
return render_template('index.html', mylist=['one', 'two', 'three'],
                           listdict=[{'name': 'Ahmad'}])

list :

{% for x in mylist %}
<h3>{{ x }}</h3>
{% endfor %}

dictionary :

{% for y in listdict %}
<h3>{{ y.name }}</h3>
{% endfor %}

Templating HTML syntax

{{ data['code']|safe }}

# add |safe 

Leave a Reply

Your email address will not be published. Required fields are marked *