简体   繁体   中英

Multiple CSS files in Flask?

How would you get your template to use a specific css file in Flask?

admin.html = admin.css  
user.html = user.css

I've looked at the Flask docs and they don't make sense?

You can overwrite the <head> section in your base template in a child template. So every user page use the css file from the base.html template and only the admin.html use the other file. This is documented in http://flask.pocoo.org/docs/patterns/templateinheritance/#template-inheritance

Edit: Maybe you can use this: All pages derive from base.html and use base.css. Only user.html and admin.html overwrite the head section and include base.css and the specific admin.css / user.css.

Example :

base.html:

     <!doctype html>
     <html>
     <head>
      {% block head %}
        <link rel="stylesheet" href="{{ url_for('static', filename='base.css') }}">
      {% endblock %}
      </head>
      <body>
      <div id="content">{% block content %}{% endblock %}</div>

     </body>
     </html>

admin.html:

    {% extends "base.html" %}
    {% block head %}
      <link rel="stylesheet" href="{{ url_for('static', filename='base.css') }}">
      <link rel="stylesheet" href="{{ url_for('static', filename='admin.css') }}">
    {% endblock %}
    {% block content %}
     content goes here
    {% endblock %}

user.html:

    {% extends "base.html" %}
    {% block head %}
      <link rel="stylesheet" href="{{ url_for('static', filename='base.css') }}">
      <link rel="stylesheet" href="{{ url_for('static', filename='user.css') }}">
    {% endblock %}
    {% block content %}
     content goes here
    {% endblock %}

Edit: If you store your css files in a sub directory of static/ you must write the link like this:

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

You can pass the css file to use to the template as a variable.

{'css_file': 'admin.css'}

Then use it in the template:

<link rel="stylesheet" href="/css/{{ css_file }}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM