Introduction to Tornado (3): Development using templates [Practice]

Introduction

In this series, I will introduce how to develop applications with Tornado, which is a web server & web application framework that runs on Python. The contents of this series are as follows.

Last time, I explained how to pass a value from a handler to a template. This enables dynamic content generation. This time, I will explain the functions of further templates. Specifically, I will explain how to build an application using template inheritance.

<!-This time, I will introduce the template engine function of Tornado. ->

Target audience

Required environment

Related article

Sample code

Last review

In Previous article, I created an application that displays something like "Hello your name!" When you pass a name. Through the creation of this application, I understood the basics of dynamic page generation. スクリーンショット 2015-10-26 16.01.02.png

Last time there was only one template file. However, most real web applications use multiple templates. So, this time, I will try to develop using multiple templates.

This time we will create a programming language introduction site. The image is as follows.

sample.jpg

This time, I will make it after learning the mechanism of template inheritance.

Template inheritance

Template inheritance is the ability to ** inherit an existing template and create a new template **. We will call the existing template ** parent template ** and the inherited template ** child template **.

In template inheritance, the parent template contains elements that are commonly used on your site, and a block that can be overwritten by the child template is defined in it. This allows the parent template to be reused. Let's look at an example.

base.html


<html>
  <head>
    <title>{% block title %}Default title{% end %}</title>
  </head>
  <body>
    {% block content %}
Default content
    {% end %}
  </body>
</html>

Let's call this template base.html. In this example, we use the block tag to define two blocks ({% block title%} {% end%} and {% block content%} {% end%}) so that the child template can be filled with values. I have. The role of the block tag is to inform the template engine that the part of the template enclosed by the tags can be overwritten by the child template.

The child template looks like this:

{% extends "base.html" %}

{% block content %}
Child template content
{% end %}

The extends tag at the top is the key to inheritance. This tag tells the template engine that it is extending itself to other templates. When the template engine processes this template, it first looks for the parent template (here base.html).

At this point, the template engine notices that two blocks are defined in base.html and replaces these blocks with the appropriate blocks in the child template. The output looks like this:

<html>
  <head>
    <title>Default title</title>
  </head>
  <body>
Child template content
  </body>
</html>

The child template does not have a title block defined, so the value of the parent template is used as is.

Creating an application

Directory structure

The directory structure is almost the same as last time. The difference is that some files have been added to templates.

.
├── app.py
├── static
│   └── style.css
└── templates
    ├── base.html
    ├── index.html
    ├── php.html
    ├── python.html
    └── ruby.html

The files in templates are parent templates that inherit from base.html, and the others are child templates that are created by inheriting base.html. As a function, index.html is the top page, and the others are introduction pages for each language.

Same as last time, there are the following three components.

Python code

The Python code to be executed this time is as follows.

import os
import tornado.ioloop
import tornado.web
from tornado.web import url


class IndexHandler(tornado.web.RequestHandler):

    def get(self):
        self.render('index.html')


class PythonHandler(tornado.web.RequestHandler):

    def get(self):
        self.render('python.html')


class PHPHandler(tornado.web.RequestHandler):

    def get(self):
        self.render('php.html')


class RubyHandler(tornado.web.RequestHandler):

    def get(self):
        self.render('ruby.html')


BASE_DIR = os.path.dirname(__file__)

application = tornado.web.Application([
    url(r'/', IndexHandler, name='index'),
    url(r'/python/', PythonHandler, name='python'),
    url(r'/php/', PHPHandler, name='php'),
    url(r'/ruby/', RubyHandler, name='ruby'),
    ],
    template_path=os.path.join(BASE_DIR, 'templates'),
    static_path=os.path.join(BASE_DIR, 'static'),
)

if __name__ == '__main__':
    application.listen(8888)
    tornado.ioloop.IOLoop.current().start()

I haven't done anything new since last time. One new thing is that you use the url function when setting the URL and pass name as an argument. This allows you to do a reverse URL lookup. Reverse URL lookup is an image that ** when you pass a name to the reverse lookup function, it is converted to the URL corresponding to that name **. For example, in the case of URL setting like this time, if you pass the character string "python" to the function for reverse lookup, it will be converted to the URL "/ python /". The reason this is possible is that when you set the URL "/ python /" using the url function, you pass the string "python" in its name argument. In addition, reverse lookup is used in the template.

template

The following 5 templates are used for display this time. First, base.html. This is the parent template this time.

base.html


<!DOCTYPE html>
<html lang="ja">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">

      <title>{% block title %}{% end %}</title>

      <!-- CSS -->
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
      <link href="{{ static_url('style.css') }}" rel="stylesheet">

    </head>

    <body>

        <nav class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <a class="navbar-brand" href="{{ reverse_url('index') }}">Home</a>
                    <a class="navbar-brand" href="{{ reverse_url('python') }}">Python</a>
                    <a class="navbar-brand" href="{{ reverse_url('php') }}">PHP</a>
                    <a class="navbar-brand" href="{{ reverse_url('ruby') }}">Ruby</a>
                </div>
            </div>
        </nav>

        <div class="jumbotron">
            <div class="container">
                {% block content %}
                {% end %}
            </div>
        </div>

        <div class="container">
            <footer>
                <p>&copy; Company 2015</p>
            </footer>
        </div>

        <!-- JavaScript -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

    </body>
</html>

This template file defines two blocks ({% block title%} {% end%} and {% block content%} {% end%}). These two blocks are replaced by the child template. Also, can you see that the reverse_url function is used in the navigation bar part? This function is for performing the reverse lookup of the URL explained earlier.

Next, index.html. It is created by inheriting base.html. It functions as the top page.

index.html


{% extends "base.html" %}
{% block title %}top page{% end %}
{% block content %}
    <h1>Introduction of programming languages</h1>
    <p>
Hello! This site introduces programming languages.
Specifically, there are three: Python, PHP, and Ruby.
Select the language you are interested in from the menu above to see more details.
    </p>
{% end %}

Make sure you use extends to inherit from base.html and use block to replace the content.

And php.html, python.html, ruby.html. These are also created by inheriting base.html. Each functions as an introduction page for each language.

php.html


{% extends "base.html" %}
{% block title %}Introducing PHP{% end %}
{% block content %}
    <h1>Hello, PHP!</h1>
    <p>
PHP is a programming language whose main purpose is to realize dynamic web pages by dynamically generating HTML data.
And its language processing system. Commonly abbreviated as PHP, which means "personal home page" in English
        "Personal Home Page"Derived from.
    </p>
    <p><a class="btn btn-primary btn-lg" href="https://secure.php.net/" role="button">Know more&raquo;</a></p>
{% end %}

python.html


{% extends "base.html" %}
{% block title %}Introduction to Python{% end %}
{% block content %}
    <h1>Hello, Python!</h1>
    <p>
Python is a widely used general-purpose programming language.
It is claimed that the language is designed for high code readability, and thanks to its syntax, compared to languages such as C,
It is claimed that the program can be represented with a smaller number of lines of code. From small programs to large programs
A lot of code is provided so that you can write various programs clearly.
    </p>
    <p><a class="btn btn-primary btn-lg" href="https://www.python.org/" role="button">Know more&raquo;</a></p>
{% end %}

ruby.html


{% extends "base.html" %}
{% block title %}Introducing Ruby{% end %}
{% block content %}
    <h1>Hello, Ruby!</h1>
    <p>
Ruby is an object-oriented scripting language developed by Yukihiro Matsumoto (commonly known as Matz).
Achieve object-oriented programming in areas where scripting languages have been used.
It was also the first programming language developed in Japan to be certified as an international standard at the International Electrotechnical Commission.
    </p>
    <p><a class="btn btn-primary btn-lg" href="https://www.ruby-lang.org/ja/" role="button">Know more&raquo;</a></p>
{% end %}

Like index.html, they are created by inheriting base.html using extends and replacing the contents using block.

CSS The CSS file used this time is as follows.

body {
  padding-top: 50px;
  padding-bottom: 20px;
}

There is nothing special to say, so I will omit the explanation of this CSS file.

Run

Just like last time, run the following code to start the server.

$ python app.py

Then go to [http: // localhost: 8888 /](http: // localhost: 8888 /). You should see a page like the one below. result.png

Try selecting a programming language name in the navigation bar. You can see that the page was generated using template inheritance.

Summary

This time, I introduced how to build an application using template inheritance. You can see that you can use extends to inherit a template and block to replace the contents of a block from a child template.

If you can understand how to pass values from the handler introduced last time and how to inherit it introduced this time, you can say that you understand the basics of development using templates. After that, if you know the control statements and functions that can be used in the template, you can develop smoothly. Next time, I will introduce the control statements and functions that can be used in the template.

Reference material

Recommended Posts

Introduction to Tornado (3): Development using templates [Practice]
Introduction to Tornado (2): Introduction to development using templates-Dynamic page generation-
Introduction to discord.py (3) Using voice
Practice! !! Introduction to Python (Type Hints)
Introduction to Discrete Event Simulation Using Python # 1
Web-WF Python Tornado Part 3 (Introduction to Openpyexcel)
[PyTorch] Introduction to document classification using BERT
Introduction to Discrete Event Simulation Using Python # 2
Introduction to MQTT (Introduction)
Introduction to Scrapy (1)
Introduction to Scrapy (3)
Introduction to Supervisor
Introduction to Tkinter 1: Introduction
Flask development introduction
Introduction to Tornado (1): Python web framework started with Tornado
[PyTorch] Introduction to Japanese document classification using BERT
Introduction to PyQt
Introduction to Scrapy (2)
[Linux] Introduction to Linux
Introduction to Scrapy (4)
Introduction to discord.py (2)
Introduction to Scapy ② (ICMP, HTTP (TCP) transmission using Scapy)
Introduction to discord.py
Understand Python for Pepper development. -Introduction to Python Box-
Python development environment construction 2020 [From Python installation to poetry introduction]
[Introduction to Python] How to stop the loop using break?
[Introduction to Python] How to write repetitive statements using for statements
What I was addicted to when using Python tornado
[Technical book] Introduction to data analysis using Python -1 Chapter Introduction-
Introduction to Lightning pytorch
Introduction to Web Scraping
Introduction to Nonparametric Bayes
Introduction to EV3 / MicroPython
Introduction to Python language
Introduction to OpenCV (python)-(2)
Introduction to PyQt4 Part 1
Type-aware using c ++ templates
Introduction to Dependency Injection
Introduction to Private Chainer
Introduction to machine learning
[Introduction to Python] How to write conditional branches using if statements
Day 67 [Introduction to Kaggle] Have you tried using Random Forest?
Introduction to Bayesian Modeling Using pymc3 Bayesian-Modeling-in-Python Japanese Translation (Chapter 0-2)
[Python] Introduction to graph creation using coronavirus data [For beginners]