Django: How to create a template

In your app folder, create a new directory called "templates\appname" where appname is the name of the app you're creating the template for.

Now, create a new file which has a relevant name. For this example, I'll just use "app_template_example.html".

Fill it up with any sort of output you want such as HTML, Javascript or CSS.

{% if user.is_authenticated %}
<a href="#" onclick="login(); return false;">Login</a>
{% else %}
<a href="#" onclick="user_panel(); return false;">{{ user.username }}</a>
<a href="#" onclick="logout(); return false;">Logout</a>
{% endif %}

Now, this will print out one of either cases. If you're logged in, it'll display a login link. Otherwise, it'll display a link to your user panel with the title of your account name and a logout link.

A simple view handler can provide you with information such as "user" and anything else you'd like. It also tells your app which template to use.

from django.shortcuts import render_to_response

def example_view(request):
    return render_to_response('appname/app_template_example.html', { 'user' : request.user, 'custom_field': 'blah blah blah...' })

Now open the view in the browser and it should display the template. To do that, see the tutorial on how to create Django views.

Lastly, just edit the template and include "{{ custom_field }}" anywhere you like. Refresh the page and you'll be able to see how easy it is to feed more information into the template.

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog