{"id":2543,"date":"2024-10-22T13:00:06","date_gmt":"2024-10-22T13:00:06","guid":{"rendered":"http:\/\/suimy.me\/?p=2543"},"modified":"2024-10-23T17:07:47","modified_gmt":"2024-10-23T17:07:47","slug":"how-to-render-templates-in-flask","status":"publish","type":"post","link":"http:\/\/suimy.me\/index.php\/2024\/10\/22\/how-to-render-templates-in-flask\/","title":{"rendered":"How to Render Templates in Flask"},"content":{"rendered":"

p>Flask<\/strong> is a lightweight web framework for Python that makes it easy to build web applications. In our previous article, we\u2019ve seen how to set up a simple page<\/a>.<\/p>\n

But, it\u2019s just a simple text like \u201cHello Flask!\u201d<\/strong>. In real applications, you\u2019ll want to render more than just simple text. You\u2019ll want to render HTML templates.<\/p>\n

In Flask, we can do so with Jinja<\/a><\/strong>.<\/p>\n

\"\"\"\"<\/span><\/span> <\/figure>\n

Jinja<\/h4>\n

One of its powerful features is the ability to render HTML templates using the Jinja templating engine.<\/p>\n

Jinja templates are written in regular HTML that you are already familiar with. But, on top of that, you can use special syntax to handle dynamic content, such as for passing data from requests or other code sources to the template. It also allows you to use control structures like loops and conditionals.<\/p>\n

Let\u2019s see how it works in its basic form:<\/p>\n

\r\n\r\n\r\n\r\n    Welcome to Flask<\/title>\r\n\r\n\r\n    {% if user.is_logged_in %}\r\n        <p>Welcome back, {{ user.name }}!<\/p>\r\n    {% else %}\r\n        <p>Please log in to continue.<\/p>\r\n    {% endif %}\r\n\r\n\r\n<\/pre>\n<p>It looks like a regular HTML file, but as we can see, we use some special syntax, such as the <code>{{ }}<\/code> to insert a variable, and we use <code>{% %}<\/code> for adding loops and conditionals.<\/p>\n<h4>Rendering the Templates<\/h4>\n<p>To render the template, we need to put it in the <code>templates<\/code> directory.<\/p>\n<pre class=\"terminal\">\r\n.\r\n|-- app.py\r\n|-- templates\r\n    |-- about.html\r\n    |-- index.html\r\n<\/pre>\n<p>Then, we use the <code>render_template<\/code> function in our Python app file to render HTML templates. If we extend the same code from <a href=\"https:\/\/www.hongkiat.com\/blog\/getting-started-with-flask\/\">our previous article<\/a>, our code would now look like the following:<\/p>\n<pre class=\"terminal\">\r\nfrom flask import Flask, render_template\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('\/')\r\ndef home():\r\n    return render_template('index.html')\r\n\r\n@app.route('\/about')\r\ndef about():\r\n    return render_template('about.html')\r\n<\/pre>\n<h5>Passing Variables<\/h5>\n<p>In our template above, we have <code>{{ name }}<\/code> and <code>{{ user.is_logged_in }}<\/code> variables. But, we haven\u2019t passed any variables to the template yet.<\/p>\n<p>To pass variables to the template, we can do so by passing them as arguments to the <code>render_template<\/code> function.<\/p>\n<p>For example:<\/p>\n<pre class=\"terminal\">\r\n@app.route('\/')\r\ndef home():\r\n    return render_template('index.html', user={'is_logged_in': True, 'name': 'Joann'})\r\n<\/pre>\n<p>Now, when we visit the home page, we will see the <strong>\u201cWelcome back, Joann!\u201d<\/strong> message instead of <strong>\u201cPlease log in to continue.\u201d<\/strong> because the <code>is_logged_in<\/code> is set to <code>True<\/code>.<\/p>\n<h5>Template Inheritance<\/h5>\n<p>Jinja allows you to use template inheritance, which is helpful when multiple pages share the same layout or components. Instead of repeating common elements, we can create a base template and reuse it in other templates.<\/p>\n<p>In this example, we have a homepage and an about page that share the same layout, like the <code>head<\/code>, <code>title<\/code>, and maybe some styles or scripts later on. With template inheritance, we can make things simpler and more organized.<\/p>\n<p>First, we create the base file. Let\u2019s name it <code>base.html<\/code>. Then, add the common elements:<\/p>\n<pre class=\"terminal\">\r\n\r\n\r\n\r\n    <title>{% block title %}Welcome to Flask{% endblock %}<\/title>\r\n\r\n\r\n    {% block content %}{% endblock %}\r\n\r\n\r\n<\/pre>\n<p>In this template, there are two blocks: one for the title and one for the content. The <code>{% block %}<\/code> tag allows child templates to override specific sections of the base template.<\/p>\n<p>Now, we can rewrite the <code>index.html<\/code> file to extend the <code>base.html<\/code> file. We can remove all of the basic HTML structure, like the <code>head<\/code> and <code>title<\/code> tags from the <code>index.html<\/code> file, and replace it with the <code>extends<\/code> tag.<\/p>\n<pre class=\"terminal\">\r\n{% extends 'base.html' %}\n\n{% block title %}Welcome to Flask{% endblock %}\n\n{% block content %}\n{% if user.is_logged_in %}\n    <p>Welcome back, {{ user.name }}!<\/p>\n{% else %}\n    <p>Please log in to continue.<\/p>\n{% endif %}\n{% endblock %}\r\n<\/pre>\n<p>On the about page, we could also rewrite it as follows:<\/p>\n<pre class=\"terminal\">\r\n{% extends 'base.html' %}\r\n\r\n{% block title %}About Us{% endblock %}\r\n\r\n{% block content %}\r\n    <p>This is the about page.<\/p>\r\n{% endblock %}\r\n<\/pre>\n<p>When we visit the homepage, we\u2019ll see the <strong>\u201cWelcome back, Joann!\u201d<\/strong> message if the user is logged in. On the about page, we\u2019ll see <strong>\u201cThis is the about page.\u201d<\/strong>. The difference here is that both pages are cleaner and easier to maintain, without repeating code.<\/p>\n<h4>Wrapping Up<\/h4>\n<p>That\u2019s how we can render HTML templates in Flask using Jinja. Jinja is a powerful templating engine that comes with helpful features and <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/jinja.palletsprojects.com\/en\/3.1.x\/extensions\/\">extensions<\/a>, making it easier to build dynamic web applications in Python.<\/p>\n<p>There\u2019s still a lot more to explore, but I hope this article gives you a solid starting point to get up and running with Flask.<\/p>\n<p>The post <a href=\"https:\/\/www.hongkiat.com\/blog\/flask-render-html-templates-jinja\/\">How to Render Templates in Flask<\/a> appeared first on <a href=\"https:\/\/www.hongkiat.com\/blog\">Hongkiat<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>p>Flask is a lightweight web framework for Python that makes it easy to build web applications. In our previous article, […]<\/p>\n","protected":false},"author":1,"featured_media":2545,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[15],"tags":[],"_links":{"self":[{"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/posts\/2543"}],"collection":[{"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/comments?post=2543"}],"version-history":[{"count":2,"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/posts\/2543\/revisions"}],"predecessor-version":[{"id":2546,"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/posts\/2543\/revisions\/2546"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/media\/2545"}],"wp:attachment":[{"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/media?parent=2543"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/categories?post=2543"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/suimy.me\/index.php\/wp-json\/wp\/v2\/tags?post=2543"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}