简体   繁体   中英

Python tornado, conditional template extension

I'm using tornadoweb to build a web service. I have two different templates that contains the html head , the navbar, and all the UI that is common to all pages server by the service. The first, base.html contains navbar items and other html elements displayed to authenticated users only. The second, base_anon.html is lighter and contains a few items that are available to anonymous users.

Now I'm creating a third template that will contain the actual content of the page. I would like this template to extend either base_anon.html or base.html depending whether a user is authenticated or not. The variable user will be Falsy if the user is not authenticated. Is there a way to do a conditional template extension?

I tried the following:

{% if user %}
    {% extends "base.html" %}
{% else %}
    {% extends "base_anon.html" %}
{% end %}

Which, when rendered by tornado generates the following stack trace (copied only the end of the stack):

Traceback (most recent call last):
  [...]
  File "[...]/lib/python2.7/site-packages/tornado/template.py", line 291, in _generate_python
    ancestors[0].generate(writer)
  File "[...]/lib/python2.7/site-packages/tornado/template.py", line 416, in generate
    self.body.generate(writer)
  File "[...]/lib/python2.7/site-packages/tornado/template.py", line 429, in generate
    chunk.generate(writer)
  File "[...]/lib/python2.7/site-packages/tornado/template.py", line 510, in generate
    self.body.generate(writer)
  File "[...]/lib/python2.7/site-packages/tornado/template.py", line 429, in generate
    chunk.generate(writer)
  File "[...]/lib/python2.7/site-packages/tornado/template.py", line 398, in generate
    raise NotImplementedError()
NotImplementedError

I do not have more information to provide that could explain this error. Neither could I find any information in the docs about a conflict between if and extends statements. Any idea why this error shows up? If this is actually expected, how else may I use a different base template depending on the value of some variable?

Thanks for reading!

It's not currently possible to do what you're asking for. If the {% extends %} directive is used it must appear at top level and its argument must be a constant; there is no way to change which template you are extending.

Instead, consider using different top-level templates depending on whether or not there is a logged-in user, and encapsulating the common elements in UIModules . Or put all of the {% if %} directives in the base template, perhaps around the {% block %} definitions.

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