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

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:

主站蜘蛛池模板: 鄂伦春自治旗| 新郑市| 双流县| 和平县| 土默特右旗| 景宁| 双流县| 瑞丽市| 花莲县| 黄平县| 沙湾县| 兴安盟| 三明市| 海宁市| 明光市| 滨州市| 莱芜市| 丹江口市| 沙坪坝区| 德保县| 彭山县| 莱西市| 封丘县| 临汾市| 中江县| 南丰县| 石狮市| 香港| 灵石县| 桐城市| 鸡西市| 民丰县| 丹凤县| 鄂州市| 内丘县| 新郑市| 佛学| 开封县| 元朗区| 阿鲁科尔沁旗| 甘肃省|