Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

How do you add classes and ids to template blocks in Flask?

I want to build a Flask site and use Bootstrap 4 for the front-end. I am confused how to add classes to specific template blocks. Anyone have any suggestions on how to properly apply styles when using Jinja templates?

2 Answers

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,731 Points

Basically, if you pass in a template variable containing a classname, it can be injected into the HTML template.

In the example below the simple flask app can pass a Bootstrap status color to a button

if you call these URLs, you will see different button styling passed into the "button" class

Here are static routes

http://localhost:5000/sucess

http://localhost:5000/danger

here are dynamic routes

http://localhost:5000/button/success

http://localhost:5000/button/info

http://localhost:5000/button/danger

app.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/success')
def success_button():
   """this is static button with success"""
    return render_template('show_button_status.html', status="success")

@app.route('/danger')
def danger_button():
   """this is static button with danger"""
    return render_template('show_button_status.html', status="danger")

@app.route('/button/<status>')
def show_button(status):
    """this is a dynamic route where the status comes in as a URL parameter"""
    return render_template('show_button_status.html', status=status)

if __name__ == '__main__':
    app.run('0.0.0.0', port=5000, debug=True)

show_button.html

NOTE: the status variable inside the quotes of the button class (as per Bootstrap rules)

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Button type {{status}}</h2>
  <p>The .btn-success, .btn-info, .btn-danger class gives styling to the button:</p>      
  <button type="button" class="btn btn-{{status}}">My Button</button>
</div>

</body>
</html>

Thanks for your explanation Jeff. I am still a bit unclear though. It would seem from your explanation that whenever I want to style an element differently I am going to have to create a dynamic route just for that element. That seems like an awful lot of work. I don't even know how that would work.

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,731 Points

Kenneth introduced MVC (Model View Controller) architechture-- and Flask programming makes it easy to build for that paradigm. But when you get to the "V" part (the Views) you find that JavaScript is where most of the client-side dynamism comes from.

Here's a nice blog post on MVC with a Flask example:

https://realpython.com/the-model-view-controller-mvc-paradigm-summarized-with-legos/

  1. Models: define how we handle data in our app. These are built with Python classes and/or ORM (such as PeeWee, SQLAlchemy, PyMongo, etc).

  2. Controller: Flask routes requests and sends responses based on the "business logic" of your application. Routing is where Flask really shines. Flask also manages sessions, cookies, and global variables (like the "g" object which is also silently passed to the template)

  3. Views: Flask renders HTML templates which are fed with data object(s) like model instances or individual non-model objects. This data is handed off to be processed further by the Jinja2 templating language. Finally, the HTML is rendered to the user at the Browser. And the HTML pages can include lots of styling with Bootstrap, Foundation, Bulma, etc. And of course JavaScript the most powerful dynamic language of all.

I can't emphasize enough, that a developer will NEED some JavaScript knowledge too! And Treehouse has some nice courses to learn lots of useful JavaScript.

I don't know if that answers your question, but you will get an opportunity to put it all in to practice in the Flask track.