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

  1. Stop the Run Tool window’s execution by clicking the red square button in the Run Tool window.

  2. Click on the templates directory and press Ctrl-N to make a new file named layout.html in the templates directory.

  3. Use Emmet to fill in the HTML for this directory: html>head>title then tab.

  4. In the <title> type in Todo: {{ title }}.

  5. Use Emmet for the body. After </head> type in: body>h1>a then press tab.

  6. In the <h1>: <a href="/">Home</a></h1>.

  7. Press Shift-Enter and add:

    <h2>{{ title }}</h2>
    {% block content %}
    {% endblock %}
    </body>
    
  8. Right-click on templates/index.html and choose Refactor-Rename to change the name to home_page.html.

  9. Right-click in the editor tab for app.py and choose Debug.

  10. (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.

  11. Reload browser on the root URL.

  12. Your app.py should 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)
    
  13. Your templates/layout.html should 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>
    
  14. Your templates/home_page.html should match the following:

    templates/home_page.html in Master
    {% extends "layout.html" %}
    {% block content %}
        <p><a href="/todo/">Todos</a></p>
    {% endblock %}