- Render HTML templates
- Pass variables from URL routes
- Style pages using Jinja
Open the portfolio project directory that you created last time.
- Create a new folder named
templates.
mkdir templatesThis is where we'll place all of the HTML templates that we'll create later on.
- Create a new folder named
staticwith subfolders namedcssandjs.
mkdir static
cd static
mkdir css
mkdir js
cd ..This is where we'll place all of our CSS and JS files.
Your project directory should now contain the following:
- Create a file named
about.htmland place it inside the templates folder.
<h1>Welcome to the About page.</h1>- Open
app.pyand renderabout.htmlinside youraboutfunction by replacing the return stringAboutwithrender_template(file_name).
from flask import render_template
@app.route("/about/")
def about():
return render_template("about.html")If you try to access <URL>/about/, the contents of about.html will be displayed.
You may remove your about_location() function since we won't be using it anymore.
- Create a file named
layout.htmland place it inside the templates folder.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body></body>
</html>- Check out the following links and save them inside your
staticfolder:
- Inside the head tag of your
layout.html, add atitleand reference your CSS files.
<title>Your Name</title>
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">The url_for() function is used to get the relative path of a file.
- Reference your JS files inside the body tag.
<script src="{{ url_for('static', filename='js/jquery-3.3.1.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>- Add a navigation bar inside the body tag as well. Make sure that the JS references are located at the bottom most part of the body.
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="{{ url_for('home') }}">Your Name</a>
</div>
<ul class="nav navbar-nav">
<li><a href="{{ url_for('about') }}">About</a></li>
<li><a href="{{ url_for('skills') }}">Skills</a></li>
<li><a href="{{ url_for('projects') }}">Projects</a></li>
<li><a href="{{ url_for('contact') }}">Contact</a></li>
</ul>
</div>
</nav>The url_for() function can also be used to get the relative path and URL route of the functions in your app.py. In this case, url_for('about') refers to <URL>/about/.
- Add a block named
bodybelow the navigation bar.
{% block body %}{% endblock %}Blocks are used to load dynamic content on a static page.
- Go back to your
app.py. Add an optional string inputusernameto theskillsfunction and set the default value toNone.
@app.route("/skills/", defaults={'username': None})
@app.route("/skills/<string:username>/")
def skills():
return "Skills"- Allow the
skillsfunction to accept theusernamevariable and replace the return string with a renderedskills.htmltemplate that accepts the variableusername.
@app.route("/skills/", defaults={'username': None})
@app.route("/skills/<string:username>/")
def skills(username):
return render_template("skills.html", username=username)A variable can be passed to a template by referencing it as a second parameter of the render_template() function.
You may remove your skills_toeic() function since we won't be using it anymore.
- Since we don't have
skills.htmlyet, create it and place it inside thetemplatesfolder.
<h1>Welcome to the Skills page.</h1>- To utilize the
layout.htmlthat we made earlier, extend it inside yourskills.htmland put your welcome header inside thebodyblock.
{% extends "layout.html" %}
{% block body %}
<h1>Welcome to the Skills page.</h1>
{% endblock %}Contents added in between the block tags are loaded with the layout page specified. If you try to access <URL>/skills/, the contents of layout.html and skills.html will be displayed.
- To use the variable
usernameinsideskills.html, encase the variable name inside double curly braces.
<p>
Hi, {{username|title}}!
</p>Use the title keyword to make the first letter of each word capitalized.
- What happens when the value of
usernameisNone? Use an if-else statement with Jinja to handle this problem.
<p>
{% if username == None %}
Hi, stranger. What\'s your name?
{% else %}
Hi, {{username|title}}!
{% endif %}
</p>If you try to access <URL>/skills/ without an input, it will now display the message:
Hi, stranger. What's your name?
- Go back to your
app.py. Remove the optional integer inputamountfrom the URL routes ofprojectsfunction and renderprojects.htmlinstead.
@app.route("/projects/")
def projects():
return render_template("projects.html")- Inside the
projectsfunction, define a list of projects inside the variableprojects.
projects = ["Facebook", "Twitter", "Instagram", "Uber", "Grab"]- Import
randint()fromrandomand use it to assign a random integer to a variable namedrandNo.
Add this to the top part of your code:
from random import randintAdd this inside projects function:
randNo = randint(0, len(projects) - 1)The first parameter of randint() refers to the lowest possible number while the second parameter refers to the highest possible number, which is equal to the number of projects minus 1 since we started counting from 0.
- Create a variable named
projectwhich contains a random project from the list of projects and pass all the variables toprojects.html.
project = projects[randNo]
return render_template("projects.html", **locals())The **locals keyword is used to pass multiple variables.
- Create
projects.htmlinside the static folder with the same structure asskills.html.
{% extends "layout.html" %}
{% block body %}
<h1>Welcome to the Projects page.</h1>
{% endblock %}- Finally, use the variables that we created earlier inside the
projectsfunction while utilizing the for loop statement.
<h3> These are what I\'ve done so far:</h3>
<ul>
{% for p in projects %}
<li>{{ p }}</li>
{% endfor %}
</ul>
<p>... and <b>{{ project }}</b> is the one that I enjoyed coding the most.</p>This displays a bulleted list of projects and the randomly selected project as follows:
There are what I've done so far:
- Uber
- Grab
... and Facebook is the one that I enjoyed coding the most.
You're halfway through the entire tutorial. Now try to create a template for all of your existing pages and feel free to customize them and their contents!
