Domanda

I would like to output different templates for the front page of my webapp depending on the role of the logged in user.

I have two types of 'Accounts' structured using the PolyModel data model:

class Account(polymodel.PolyModel):
    username = ndb.StringProperty(required = True)
    pw_hash = ndb.StringProperty(required = True)
    email = ndb.StringProperty(required = True)

class Farmer(Account):
    name = ndb.StringProperty(required = True)

class FarmCompany(Account):
    name = ndb.StringProperty(required = True)

The app's homepage ('/') is index.html which inherits from base.html using jinja2:

base.html:

<!DOCTYPE html>
<html>
    <head>
      <title>Farmers App</title>
    </head>
    <body>
        {% block content %}  
        {% endblock %}
    </body>
</html>

index.html:

{% extends "base.html" %}
{% block content %}
    {{ content }}
{% endblock %}

Now, because I've used the PolyModel data structure, the each 'Account' entity is stored as the following:

Farmer 'Account' Entity example:

Farmer(
    key=Key('Account', 5066549580791808), 
    class_=[u'Account', u'SkilledPerson'],
    name=u'Haopei', ...)

FarmCompany 'Account' Entity example:

FarmCompany(
    key=Key('Account', 6863449581091834), 
    class_=[u'Account', u'FarmCompany'],  
    name=u'Big Farm Company', ...)

This means I can get the Account type with a function like this:

def check_user_role_by_uid(self, uid):
    user = Account.get_by_id(uid)
    return user.class_[1] #returns 'Farmer' or 'FarmCompany'

So my question is:

How do I create two separate 'index.html' to be used depending on whether the logged in user is a 'Farmer' or a 'FarmCompany'?

È stato utile?

Soluzione 2

You would create two separate versions of index.html. Let's call them index_farm.html and index_farmcompany.html.

Then in your handler, you'd use the appropriate version:

class myHandler(webapp2.RequestHandler): 
    def get(self):
        # somehow get account uiod
        type =  Account.check_user_role_by_uid(uid)
        if type == 'SkilledPerson':
            self.render('index_farm.html')
        elif type == 'FarmCompany':
            self.render('index_farmcompany.html')

Altri suggerimenti

A different approach: In python you can send account_type as a parameter. For example:

 return {'account': check_user_role_by_uid(uid)}

With jinja2 you can select the correct template, reuse HTML and add particular code for each account. If afterwards you have more accounts, it's easier to extend

index.html
{% if account == 'Farmer' %}
  {% extends "farmer_base.html" %} {# you can extend from different base #}
{% else %}
  {% extends "farmcompany_base.html" %}
{% endif %}

{% block content %}
    {{ content }}
    {% if account == 'Farmer' %}
      {# Some Farmer stuff #} {# or you can add particular code for an account #}
     {% endif %}
{% endblock %}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top