Render HTML Template In Flask With CSS And JavaScript In 2022

How to Render HTML Template in Flask Using Custom CSS and JS File - Python Flask - render_template - Create Web Application Using Flask

Render HTML Template In Flask With CSS And JavaScript In 2022

This article will show how we can render an HTML template in Flask with custom CSS and JavaScript. Python Flask is a module of Python that allows us to build web-based applications, APIs, etc. Flask has three main dependencies.

Flask is a backend web framework based on the Python programming language. It basically allows the creation of web applications in a Pythonic syntax and concepts. With Flask, we can use Python libraries and tools in our web applications. Using Flask we can set up a web server to load up some basic HTML templates along with Jinja2 templating syntax.

Check my article Python Flask Tutorial For Beginners- A Step-By-Step Guide 2022 for a complete setup of the Flask environment.

Open The Editor And Create A Basic HTML Template To Render Using Flask

Using any code editor or notepad, copy and paste the below code and save the file with the name “index.html”.

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
   <div class="slideshow-container">
      <button class="prev" onclick="plusSlides(-1)">Prev</button>
      <button class="next" onclick="plusSlides(1)">Next</button>
      <div class="mySlides fade">
         <div class="numbertext">1 / 4</div>
         <img src="{{ url_for('static', filename='Images/Dog-01.jpg') }}" style="width:50%">
         <div class="text">Dog</div>
      </div>
      <div class="mySlides fade">
            <div class="numbertext">2 / 4</div>
            <img src="{{ url_for('static', filename='Images/Panda-01.jpg') }}" style="width:50%;">
            <div class="text">Panda</div>
      </div>
      <div class="mySlides fade">
            <div class="numbertext">3 / 4</div>
            <img src="{{ url_for('static', filename='Images/Dog-02.jpg') }}" style="width:50%">
            <div class="text">Dog</div>
      </div>
      <div class="mySlides fade">
            <div class="numbertext">4 / 4</div>
            <img src="{{ url_for('static', filename='Images/Panda-02.jpg') }}" style="width:50%">
            <div class="text">Panda</div>
      </div>

   </div>
   <br>
   <div style="text-align:center">
      <span class="dot" onclick="currentSlide(1)"></span>
      <span class="dot" onclick="currentSlide(2)"></span>
      <span class="dot" onclick="currentSlide(3)"></span>
      <span class="dot" onclick="currentSlide(4)"></span>
   </div>
   <script src="{{ url_for('static', filename='app.js') }}"></script>
</body>
</html>

Create A CSS File For Styling The Rendered Template

Add styling to the Slide Show by creating a CSS file. Just copy and paste the below code and save the file with the name “style.css”.

For more information on Flask render_template, visit the official documentation.

      * {box-sizing: border-box}
      body {font-family: Verdana, sans-serif; margin:0}
      .mySlides {display: none}
      img {vertical-align: middle;}
      /* Slideshow container */
      .slideshow-container {
         max-width: 100px;
         position: relative;
         margin: auto;
      }
      /* Next & previous buttons */
      .prev, .next {
         cursor: pointer;
         position: absolute;
         top: 50%;
         width: auto;
         padding: 16px;
         margin-top: -22px;
         color: white;
         font-weight: bold;
         font-size: 18px;
         transition: 0.6s ease;
         border-radius: 20px 3px 3px 0;
         user-select: none;
      }
      /* Position the "next button" to the right */
      .next {
         right: 0;
         border-radius: 3px 0 0 3px;
      }
      /* On hover, add a black background color with a little bit seethrough */
      .prev:hover, .next:hover {
         background-color: rgba(0,0,0,0.8);
      }
      /* Caption text */
      .text {
         color: black;
         font-size: 15px;
         padding: 8px 12px;
         position: absolute;
         bottom: 8px;
         width: 100%;
         text-align: center;
      }
      /* Number text (1/3 etc) */
      .numbertext {
         color: #f2f2f2;
         font-size: 12px;
         padding: 8px 12px;
         position: absolute;
         top: 0;
      }
      /* The dots/bullets/indicators */
      .dot {
         cursor: pointer;
         height: 15px;
         width: 15px;
         margin: 0 2px;
         background-color: #bbb;
         border-radius: 50%;
         display: inline-block;
         transition: background-color 0.6s ease;
      }
      .active, .dot:hover {
         background-color: #717171;
      }

Write A JavaScript File To Add Logics In The Rendered Template

Just like above, copy and paste the below code and save the file with the name “app.js”.

var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
   showSlides(slideIndex += n);
}
function currentSlide(n) {
   showSlides(slideIndex = n);
}
function showSlides(n) {
   var i;
   var slides = document.getElementsByClassName("mySlides");
   var dots = document.getElementsByClassName("dot");
   if (n > slides.length) {slideIndex = 1}
   if (n < 1) {slideIndex = slides.length}
   for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
   }
   for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
   }
   slides[slideIndex-1].style.display = "block";
   dots[slideIndex-1].className += " active";
}

Make Sure To Structure The Files In the Following Format

The above-saved files should be stored locally in the below format. All the static files such as images, JavaScript, CSS, etc will go into the static folder. The “index.html” file will go into the templates folder. Please note, the Jupyter Notebook or Python file should be available outside the static and templates folder.

Render HTML Template In Flask
Flask Web App- Files/ Folder Structure

Create A Basic Flask App To Render The Above Template

Open Jupyter Notebook and copy and paste the below code. Please make sure that you have installed the Flask library. Save the file in the Slide Show folder as shown in the above image.

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

if __name__ == "__main__":
    app.run()

After writing the above code, execute the code block/ cell.

Python Flask Application- Rendering HTML Template
Python Flask Application- Rendering HTML Template

Click on the link in a new tab (highlighted in yellow).

Output

In the output, the slide show with four different images is shown. There are two buttons- Prev and Next using which you can change the images.

Summary

In this article, we discussed the basics of template rendering using the Python Flask module. We created a basic Slide Show app using HTML, CSS, and JavaScript and rendered using the Flask module in Jupyter Notebook. The source code is available for free for re-use. We can also build Machine Learning based applications and run them in the browser, WordPress, or even Blogger. In the next article, we will discuss these topics. Please stay tuned!