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
templatesdirectory and pressCtrl-Nto make a new file namedlayout.htmlin thetemplatesdirectory.Use Emmet to fill in the HTML for this directory:
html>head>titlethentab.In the
<title>type inTodo: {{ title }}.Use Emmet for the body. After
</head>type in:body>h1>athen presstab.In the
<h1>:<a href="/">Home</a></h1>.Press
Shift-Enterand add:<h2>{{ title }}</h2> {% block content %} {% endblock %} </body>
Right-click on
templates/index.htmland chooseRefactor-Renameto change the name tohome_page.html.Right-click in the editor tab for
app.pyand 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.pyshould match the following:app.py in Master¶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.htmlshould match the following:templates/layout.html in Master¶<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.htmlshould match the following:templates/home_page.html in Master¶{% extends "layout.html" %} {% block content %} <p><a href="/todo/">Todos</a></p> {% endblock %}
- Previous topic: Templates
- Next topic: List Todos Template