Master Template¶
We are going to convert some more views to use templates. Along the way, we are going to introduce PyCharm’s debugger.
Steps¶
Stop the Run Tool window’s execution by clicking the red square button in the Run Tool window.
Click on the
templates
directory and pressCtrl-N
to make a new file namedlayout.html
in thetemplates
directory.Use Emmet to fill in the HTML for this directory:
html>head>title
thentab
.In the
<title>
type inTodo: {{ title }}
.Use Emmet for the body. After
</head>
type in:body>h1>a
then presstab
.In the
<h1>
:<a href="/">Home</a></h1>
.Press
Shift-Enter
and add:<h2>{{ title }}</h2> {% block content %} {% endblock %} </body>
Right-click on
templates/index.html
and chooseRefactor-Rename
to change the name tohome_page.html
.Right-click in the editor tab for
app.py
and chooseDebug
.(OS and Linux) In the Debugger console, click on the link that says:
warning: Debugger speedups using cython not found. Run ‘”/Users/pauleveritt/virtualenvs/epc/bin/python” “/Applications/PyCharm.app/Contents/helpers/pydev/setup_cython.py” build_ext –inplace’ to build.
Reload browser on the root URL.
Your
app.py
should match the following:from flask import Flask from flask import render_template from models import populate_todos, Todo app = Flask(__name__) @app.route('/') def home_page(): return render_template('home_page.html', title='Home Page') @app.route('/todo/') def list_todos(): todos = Todo.list() div = '<div><a href="/todo/{id}">{title}</a></div>' items = [div.format(id=t.id, title=t.title) for t in todos] return '\n'.join(items) @app.route('/todo/<int:todo_id>') def show_todo(todo_id): todo = Todo.get_id(todo_id) fmt = '<h1>Todo {todo_id}</h1><p>{title}</p>' return fmt.format(todo_id=todo.id, title=todo.title) if __name__ == '__main__': populate_todos() app.run(debug=True)
Your
templates/layout.html
should match the following:<html> <head><title>Todo: {{ title }}</title></head> <body> <h1><a href="/">Home</a></h1> <h2>{{ title }}</h2> {% block content %} {% endblock %} </body></html>
Your
templates/home_page.html
should match the following:{% extends "layout.html" %} {% block content %} <p><a href="/todo/">Todos</a></p> {% endblock %}
- Previous topic: Templates
- Next topic: List Todos Template