How to not redefine the URL for static files in the bulb every time

My application has many routes that use the same set of static files.

I need to define them for each route as follows:

css_reset = url_for("static", filename="reset.css") css_main = url_for("static", filename="main.css") css_fonts = url_for("static", filename="fonts.css") js_jquery = url_for("static", filename="jquery-1.7.2.min.js") js_main = url_for("static", filename="main.js") 

And then when I create the template, it looks like this:

 return render_template("person.html", css_main=css_main, css_reset=css_reset, css_fonts=css_fonts, js_jquery=js_jquery, js_main=js_main) 

I am new to jar and python and I think that what I am doing is a little funny. Can I define them in one place and then simply use them in my templates without copying and pasting in each route definition?

+6
source share
3 answers

The easiest way is to use the Flask-Assets extension.

  from flask.ext.assets import Environment, Bundle assets = Environment(app) css_all = Bundle('reset.css','main.css','fonts.css') assets.register('css_all',css_all) 

In the template:

  {% assets %} <link rel="stylesheet" href="{{ ASSET_URL }}"> {% endassets %} 

You can also compress css and js files for production using certain options of this extension.

Since you need to use these files in many templates, define them in the base.html template and expand this base.html in each template. You do not need to write them again and again.

+12
source

Instead of passing these variables to your templates every time you can register them as global in Jinja:

 app.jinja_env.globals.update( css_reset=url_for("static", filename="reset.css"), css_main=url_for("static", filename="main.css"), ... ) 

Or better yet, register a helper function:

 app.jinja_env.globals['static'] = ( lambda filename: url_for('static', filename=filename)) 

And then in your templates:

 <link ref=stylesheet href="{{ static('main.css') }}"> 
+16
source

You do not need to do this, url_for is for generating URLs (so when you change the structure of the URL, you do not need to change it a dozen times). Instead, you can use a fixed path to your static files directly in your templates. Just put your static files in / static folder and use it in your template:

 <link rel="stylesheet" href="{{ YOUR_SITE_URL_HERE+'/static/main.css' }}"> 

Instead of directly changing YOUR_SITE_URL the URL of your site, you can define a variable in your config.py and use it in your template: {{ config['SITE_URL']+'/static/main.css' }}

-1
source

Source: https://habr.com/ru/post/921602/


All Articles