Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use a css stylesheet on a jinja2 template

I am making a website using html, css, flask and jinja2.

I have a page working on a flask server, the buttons and labels etc. are displayed, but the css stylesheet I have is not loaded in.

How would I link a stylesheet to a jinja2 template. I have looked around on the internet but cannot find out how.

Here is the css stylesheet link; should I change this, or the python code?

<link rel="stylesheet" type="text/css" href="styles.css">

here is my flask code:

@app.route('/')
def resultstemplate():
    return render_template('questions.html', head='Welcome!')

here are the locations of the files:

/python-code.py /templates/template.html /templates/styles.css

like image 354
ptolemy0 Avatar asked Jul 30 '14 10:07

ptolemy0


People also ask

Can you use Jinja2 in css?

Yes, you can do this.

How do I import a StyleSheet in css?

The @import rule allows you to import a style sheet into another style sheet. The @import rule must be at the top of the document (but after any @charset declaration). The @import rule also supports media queries, so you can allow the import to be media-dependent.

How do I import an external style sheet?

The @import rule is used for this purpose as it links a stylesheet in a document. This is generally used when one stylesheet is dependent upon another. It is specified at the top of the document after @charset declaration inside <head>.


2 Answers

All public files (the ones that are not processed, like templates or python files) should be placed into dedicated static folders. By default, Jinja2 has one static folder called static.

This should fix your problem:

  1. Move /templates/styles.css to /static/styles.css

  2. Update your code with following code, that will be translated into correct file location:

    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}"> 

More info on static files in Jinja2 is here.

like image 90
Andrejs Cainikovs Avatar answered Sep 23 '22 18:09

Andrejs Cainikovs


<link rel="stylesheet" type="text/css" href="styles.css">

href value must be within quotes.

make sure the file name and path are proper OR try the below

<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}"/>
like image 42
Sunil B N Avatar answered Sep 19 '22 18:09

Sunil B N