官术网_书友最值得收藏!

Basic use of Jinja templates

The first step to using Jinja templates is creating a directory in our application to contain our template files, so navigate to your headlines directory, and create a directory called templates. Unlike the previous steps, this name is expected by other parts of the application and is case sensitive, so take care while creating it. At the most basic level, a Jinja template can just be an HTML file, and we'll use the .html extension for all our Jinja templates. Create a new file in the templates directory called home.html. This will be the page that our users see when visiting our application, and will contain all the HTML that we previously had in a Python string.

Note

We'll only be using Jinja to build HTML files in this book, but Jinja is flexible enough for use in generating any text-based format. Although we use the .html extension for our Jinja templates, the files themselves will not always be pure HTML.

For now, put the following static HTML code into this file. We'll look at how to pass dynamic data between Python and our templates in the next step.

<html>
    <head>
        <title>Headlines</title>
    </head>
    <body>
        <h1>Headlines</h1>
        <b>title</b><br />
        <i>published</i><br />
        <p>summary</p>
    </body>
</html>

Now in our Python code, instead of building up the string and returning that in our routing function, we'll render this template and return it. In headlines.py, add an import at the top:

from flask import render_template

The render_template function is the magic which takes a Jinja template as input and produces pure HTML, capable of being read by any browser, as the output. For now, some of the magic is lost, as we'll give it pure HTML as input and view the same as output in our browser.

Rendering a basic template

In your get_news() function, remove the return statement, which contains our triple-quoted HTML string as well. Leave the previous lines which grab the data from feedparser, as we'll be using that again soon.

Update the return statement, so that the get_news() function now looks as follows:

@app.route("/")
@app.route("/<publication>"
def get_news(publication="bbc"):
  feed = feedparser.parse(RSS_FEEDS[publication])
  first_article = feed['entries'][0]
 return render_template("home.html")

Although our current HTML file is pure HTML and not yet using any of the Jinja syntax that we'll see later, we're actually already doing quite a bit of magic. This call looks in our templates directory for a file named home.html, reads this, parses any Jinja logic, and creates an HTML string to return to the user. Once you've made both the preceding changes, run your application again with python headlines.py, and navigate to localhost:5000 in your browser.

Again, we've gone a step backwards in order to advance. If you run the app and view the result in your browser now, you should see something similar to our original page, except that instead of the real news data, you'll just see the strings title, published, and summary as seen in the following image:

Let's take a look at how to populate these fields inside our render_template call so that we can see real news content again.

Passing dynamic data to our template

First, in our Python file, we'll pass each of these as named variables. Update the get_news() function again, and pass all the data that you need to display to the user as arguments to render_template(), as follows:

@app.route("/")
@app.route("/<publication>"
def get_news(publication="bbc"):
  feed = feedparser.parse(RSS_FEEDS[publication])
  first_article = feed['entries'][0]
 render_template("home.html",title=first_article.get("title"),published=first_article.get("published"),summary=first_article.get("summary"))

The render_template function takes the filename of the template as its first argument, and can then take an arbitrary number of named variables as subsequent arguments. The data in each of these variables will be available to the template, using the variable name.

Displaying dynamic data in our template

In our home.html file, we simply need to put two braces on either side of our placeholders. Change it to look like the following:

<html>
    <head>
        <title>Headlines</title>
    </head>
    <body>
        <h1>Headlines</h1>
        <b>{{title}}</b><br />
        <i>{{published}}</i><br />
        <p>{{summary}}</p>
    </body>
</html>

Double braces, {{ }}, indicate to Jinja that anything inside them should not be taken as literal HTML code. Because our placeholders, title, published, and summary, are the same as our Python variable names passed into the render_template call, just adding the surrounding braces means that the render_template call will substitute these for the real data, returning a pure HTML page. Try it out to make sure that we can see real news data again, as seen in the following image:

主站蜘蛛池模板: 郸城县| 汉川市| 大姚县| 二连浩特市| 柘城县| 山东省| 泰州市| 界首市| 灌南县| 乐平市| 枞阳县| 论坛| 晋城| 汾西县| 北票市| 财经| 茌平县| 黄梅县| 即墨市| 阿坝| 宝兴县| 大庆市| 灵川县| 延安市| 东丽区| 武陟县| 嘉黎县| 峨眉山市| 和田市| 海兴县| 定州市| 辽中县| 双城市| 乌海市| 镇宁| 靖州| 屏山县| 射阳县| 广宗县| 雷山县| 甘肃省|