Sunday, 23 August 2015

day 10 - Template

Template Loading


If you’re following along, open your settings.py and find the TEMPLATE_DIRS setting. By default, it’s an empty tuple, likely containing some auto-generated comments:
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)
"C:/project web/templates",
    # Always use forward slashes, even on Windows.
Note
Windows users, be sure to use forward slashes rather than backslashes. get_template() assumes a Unix-style file name designation.

from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    t = get_template('current_datetime.html')
    html = t.render(Context({'current_date': now}))
    return HttpResponse(html)
Moving along, create the current_datetime.html file within your template directory using the following template code:
<html><body>It is now {{ current_date }}.</body></html>
toring templates in subdirectories of your template directory is easy. In your calls to get_template(), just include the subdirectory name and a slash before the template name, like so:
t = get_template('dateapp/current_datetime.html')

or with shortcut


from django.shortcuts import render
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    return render(request, 'current_datetime.html', {'current_date': now})
The first argument to render() is the request, the second is the name of the template to use. The third argument, if given, should be a dictionary to use in creating a Context for that template. If you don’t provide a third argument, render() will use an empty dictionary.

Because render() is a small wrapper around get_template(), you can do the same thing with the second argument to render(), like this:
return render(request, 'dateapp/current_datetime.html', {'current_date': now})



No comments:

Post a Comment