django: can I write python inside html template?
{% if request.sessi开发者_如何学编程on["user_name"] %}
<div class="abcd">user has username</div>
{% else %}
<div class="abcd">user doesn't has username</div>
{% endif %}
Is it illegal? There are errors:
TemplateSyntaxError at /users/register/submit
Could not parse the remainder: '['user_name']' from 'request.session['user_name']'
Django doc says :
Django template system is not simply Python embedded into HTML
Which means that you cannot write Python.
However talking about variables, the doc also says this :
Behind the scenes
Technically, when the template system encounters a dot, it tries the following lookups, in this order:
- Dictionary lookup
- Attribute lookup
- Method call
- List-index lookup
Which means that what you are trying is possible, but the right syntax is :
{% if request.session.user_name %}
Kindly note that you need to pass the variables that are to be evaluated in the following fashion.
Your python script
template_values = {
'message': 'Invalid credentials, please try again'
'users': users
}
path = os.path.join(os.path.dirname(__file__), 'login.html')
self.response.out.write(template.render(path, template_values))
The template file
{% ifequal users.name "name" %}
<div class="abcd">user has username</div>
{% endifequal %}
Please check the django template docs for further clarification based on the version that your using.
精彩评论