Home > front end >  How to specify which css and js have to be included with Flask
How to specify which css and js have to be included with Flask

Time:09-27

I'm using Flask to develop a web application and, when I render the html page, I want to specify which css and js (external files) have to be included, based on a condition. Hence, sometimes I want to include mycss1.css and myjs1.js:

<link href="/static/css/mycss1.css" rel="stylesheet">
<script src="/static/js/myjs1.js"></script>

while sometimes I want to include mycss2.css and myjs2.js:

<link href="/static/css/mycss2.css" rel="stylesheet">
<script src="/static/js/myjs2.js"></script>

Which is the best way to do this?

For instance, can I add such arguments to render_template() function? Or can I do an "if-else" in html-js code?

CodePudding user response:

There are multiple way to do this.
You can either pass the file name in render_template or the condition on which you want to implement.

Case 1: pass the file name in render_template

render_template('template_name.html', js_file='myJsfile.js', css_file='myCssFile.css')

In HTML

<link href="/static/css/{{ css_file }}" rel="stylesheet">
<script src="/static/js/{{ js_file }}"></script>

You can pass a list of file name as well and perform loop operation for multiple file.

For loop integration. render_template('template.html', js_files=['js_file1.js', 'js_file2.js'])

{% for js in js_files %}
    <script src="/static/js/{{ js }}"></script>
{% endfor %}

Case 2: pass condition

render_template('template_name.html', condition=any_condition)

In HTML

{% if condition is True %}
   <link href="/static/css/mycss1.css" rel="stylesheet">
   <script src="/static/js/myjs1.js"></script>
{% else %}
   <link href="/static/css/mycss2.css" rel="stylesheet">
   <script src="/static/js/myjs2.js"></script>
{% endif %}

Case 3: You can save different js and different css links in separate file and based on conditions using case 1 or 2 you can include that particular file.

  • Related