background preloader

Django_templates

Facebook Twitter

Xenith/django-base-template. Use Templates in Django. This is part 4 of Webmonkey’s introductory Django tutorial.

Use Templates in Django

If you’re arriving here to learn about getting started with Django, start back at the beginning with Lesson 1. When we left off last time, we had defined some URLs for our blog and constructed a custom view to handle displaying posts by tag. If you point your browser to our development URL at this point, ( you’ll still see a Django error page complaining that the template blog/list.html does not exist. Don’t panic, it’s true — we haven’t created it yet. It’s time to tackle the last aspect of Django, the template syntax. Create some templates If you look back through the code we’ve written so far, you’ll find that we’ve point Django to a number of templates (check out the [Tutorial:Use URL Patterns and Views in Django | urlpatterns code] and the custom view we wrote).

The templates we’ve defined need to be created. Then create your list.html and detail.html files. Inheritance A simple template Open that file in your text editor. Chapter 4: Templates. In the previous chapter, you may have noticed something peculiar in how we returned the text in our example views.

Chapter 4: Templates

Namely, the HTML was hard-coded directly in our Python code, like this: def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s. </body></html>" % now return HttpResponse(html) Although this technique was convenient for the purpose of explaining how views work, it’s not a good idea to hard-code HTML directly in your views. Here’s why: Any change to the design of the page requires a change to the Python code. For these reasons, it’s much cleaner and more maintainable to separate the design of the page from the Python code itself. Template System Basics A Django template is a string of text that is intended to separate the presentation of a document from its data.

Let’s start with a simple example template. This template is basic HTML with some variables and template tags thrown in. Using the Template System Creating Template Objects. Django Templates: The Power of Inheritance. For this, the second entry in my series of posts about the Django template language (part one was an introduction), I’ve chosen to focus on its inheritance capability, which is probably its most powerful feature.

Django Templates: The Power of Inheritance

Inheritance makes it possible to whip up new pages for your site very quickly and easily. Because many of the readers of this site are bloggers themselves, I’m going to use an example of a simple blog template in an attempt to demonstrate how inheritance works in Django’s template language. With that out of the way, let’s start by throwing together some basic HTML for a blog with a header and two columns — one for content and one to act as a sidebar.