jinja2 link to static files

2024/9/19 20:48:52

I am trying to understand how to create a link to static files in jinja2.

Everything I look up relates to Flask whereas I am using just webapp2 at this stage.

My main.py file looks as follows:

import os
import urllibfrom google.appengine.api import users
from google.appengine.ext import ndbimport jinja2
import webapp2JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),extensions=['jinja2.ext.autoescape'],autoescape=True)class MainPage(webapp2.RequestHandler):def get(self): template = JINJA_ENVIRONMENT.get_template('/templates/base.html')  self.response.out.write(template.render())class ConsultsPage(webapp2.RequestHandler):def get(self):template = JINJA_ENVIRONMENT.get_template('/templates/consults.html')  self.response.out.write(template.render())class CreateConsultPage(webapp2.RequestHandler):def get(self):template = JINJA_ENVIRONMENT.get_template('/templates/create-consult.html')  self.response.out.write(template.render())app = webapp2.WSGIApplication([('/', MainPage),('/consults', ConsultsPage),('/schedule/create-consult', CreateConsultPage)
], debug=True)

My base.html template contains the links to the static files in "/css", "/js" "/images" etc.

When I look at the localhost:8080/ and localhost:8080/consults all the static files are working. Page looks fine.

However the next level in the structure localhost:8080/consults/create-consult is not linking to static files.

When I view source I see that the css link has rendered as localhost:8080/consults/css/style.css , when the actual location is localhost:8080/css/style.css.

I understand I may need to make all links dynamic via some environment variable called uri_for, but I can't find the correct way to implement this.

I tried to replace my css link with

href="{{ uri_for('static', filename='css/screen.css') }}"

I was told by App Engine uri_for not set.

Basically would like to know the correct process for setting uri_for and then how to incorporate it in the paths for my links to static files.

Any help appreciated.

Answer

uri_for() is a Flask-specific function; it matches the name static to a route, which in turn then can be used to generate a path (like /static/css/screen.css if the static route is configured to handle /static/<path:filename> urls).

You just need to hardcode the path as /css/screen.css, no need for functions.

Note the leading /; that makes it an absolute path, relative to your current host. For a page at http://localhost:8080/foo/bar, such a path is then prefixed with http://localhost:8080 to form http://localhost:8080/css/screen.css. When you deploy to the app engine, the hostname will be different.

You could store a prefix URL or path in a global, so you can easily swap out the path for a CDN later:

JINJA_ENVIRONMENT.globals['STATIC_PREFIX'] = '/'

and use that in your templates:

<style src="{{ STATIC_PREFIX }}css/screen.css"></style>

You can now alter all such URLs in one place, by setting the STATIC_PREFIX to a different value, including http://somecdn.cdnprovider.tld/prefix/.

https://en.xdnf.cn/q/72378.html

Related Q&A

How to upgrade tensorflow with GPU on google colaboratory

Currently google colaboratory uses tensorflow 1.4.1. I want to upgrade it to 1.5.0 version. Each time when i executed !pip install --upgrade tensorflow command, notebook instance succesfully upgrades t…

How to print warnings and errors when using setuptools (pip)

I am using setuptools to package code such that it can be easily installed using cd project_name && pip install .During the setup process, I want to warn the user about pre-existing config file…

TypeError: not supported between instances of State and State PYTHON 3

I am trying to utilize a PriorityQueue from the queue class. However, im having issues putting custom objects into my PQ. I have implemented the __cmp__ function below:def __cmp__(self, other):return (…

Threading and information passing -- how to

To reframe from confusion i have edited the question:one.pyimport threading count = 5 dev = threading.Thread(name=dev, target=dev,args=(workQueue,count,)) dev.setDaemon(True) dev.start() workQueue = Qu…

How to rename a node with Python LXML?

How do I rename a node using LXML? Specifically, how to rename a parent node i.e. a <body> tag while preserving all the underlying structure? I am parsing using the lxml.html module but suppos…

In python, selenium, how do I set the error messages for a wait?

I have the following code:WebDriverWait(self.driver, 20).until(expected_conditions.element_to_be_clickable(click))Now this sometimes fails and I know why it fails. But the error gives me TimeoutExcept…

Python: the mechanism behind list comprehension

When using list comprehension or the in keyword in a for loop context, i.e:for o in X:do_something_with(o)orl=[o for o in X]How does the mechanism behind in works? Which functions\methods within X do…

PRAW: Comment Submitters Username

Im developing a reddit bot that needs to know which user submitted a comment. According to the PRAW API wrapper docs, theres no specific way to get the username of a Comment objects author. Ideally I c…

Paramiko, exec_command get the output stream continuously [duplicate]

This question already has answers here:Get output from a Paramiko SSH exec_command continuously(6 answers)Closed 2 years ago.I dry on a Python script. I create a python script for a given IP will conne…

pdfminer3k has no method named create_pages in PDFPage

Since I want to move from python 2 to 3, I tried to work with pdfmine.3kr in python 3.4. It seems like they have edited everything. Their change logs do not reflect the changes they have done but I had…