Search code examples
pythonhtmlgoogle-app-enginejinja2webapp2

Why does the stylesheet not render in subpages?


When I go to /page1 I can see my stylesheet working but when I go to /page1/page2 I loose my stylesheet. I have gone to the webapp2 website and looked at the routing specifications but cant seem to make sense of it.

Folder Structure

/main.py
/index.html
/css/style.css
/templates/page1.html
/templates/page2.html


main.py

dir = os.path.dirname(__file__)
JINJA_ENVIRONMENT = jinja2.Environment(loader=jinja2.FileSystemLoader(dir),
                                       autoescape=True,
                                       extensions=['jinja2.ext.autoescape'])

class HomePage(webapp2.RequestHandler):
  def get(self):
    template = JINJA_ENVIRONMENT.get_template('index.html')
    self.response.write(template.render())

class Page1(webapp2.RequestHandler):
  def get(self):
    template = JINJA_ENVIRONMENT.get_template('templates/page1.html')
    self.response.write(template.render())

class Page2(webapp2.RequestHandler):
  def get(self):
    template = JINJA_ENVIRONMENT.get_template('templates/page2.html')
    self.response.write(template.render())

app = webapp2.WSGIApplication(
  [('/', HomePage),
   ('/page1', Page1),
   ('/page1/page2', Page2)
  ], debug=True)


index.html

<html>
  <head>
    <link rel="stylesheet" href="css/style.css" media="all">
  </head>
  <body>
    {% block section %}
    {% endblock %}
  </body>
</html>


page1.html

{% extends "index.html" %}
{% block section %}
  <p>Page 1</p>
{% endblock %}


page2.html

{% extends "index.html" %}
{% block section %}
  <p>Page 2</p>
{% endblock %}

Solution

  • You are using relative URL's for your css , which means on pages like page1/page2 the browser will try and fetch your css from /page1/css/style.css

    Change your css link to

     <link rel="stylesheet" href="/css/style.css" media="all">
    

    or set base href to /