Django -- how to use template and how to pass variables to template

Source: Internet
Author: User
How to use the template System

The most basic way to use a Django template in Python code is as follows:

  1. You can use the original template code string to createTemplateObject. Django also supports creation by specifying the template file path.TemplateObject;

  1. Call the render method of the template object and input a set of variables context. It returns a template-based display string, and the variables and labels in the template are replaced by the context value.

------------------------------ Basic method ------------------------------------

Create template object

CreateTemplateThe simplest method of an object is to instantiate it directly.TemplateClass is inDjango. TemplateIn the module, the constructor accepts a parameter, the original template code. Let's dig deeper into the python interpreter to see how it works.

When you createTemplateThe template system internally compiles the template to the internal format, optimizes the template, and prepares for rendering. If your template syntax is incorrectTemplate ()Will throwTemplatesyntaxerrorException.

Template Rendering

Once you createTemplateObject, you can useContextTo pass the data to it. A context is a collection of variables and their values.

In Django, context is representedContextClass, inDjango. TemplateModule. Her constructor has an optional parameter: a dictionary ing variable and their values. CallTemplateObjectRender ()And pass context to fill the template.

You may first consider saving the template somewhere in the file system and using the python built-in file operation function to read the file content. Assume that the file is stored in/Home/djangouser/templates/mytemplate.htmlThe Code is as follows:

from django.template import Template, Contextfrom django.http import HttpResponseimport datetimedef current_datetime(request):    now = datetime.datetime.now()    # Simple way of using templates from the filesystem.    # This is BAD because it doesn‘t account for missing files!    fp = open(‘/home/djangouser/templates/mytemplate.html‘)    t = Template(fp.read())    fp.close()    html = t.render(Context({‘current_date‘: now}))    return HttpResponse(html)

 

However, this method is not concise for the following reasons:

  • It does not deal with the loss of files. If the fileMytemplate.htmlNon-existent or unreadable,Open ()Function call will causeIoerrorException.

  • The location of the template file is hard-coded here. If you use this technology in each view function, you need to constantly copy the positions of these templates. Not to mention a large amount of input work!

  • It contains a large number of annoying duplicate code. It is called every time a template is loaded.Open (),FP. Read ()AndFP. Close (), It is better to make a better choice.

To solve these problems, we have adoptedTemplate auto-loadingAndTemplate directorySkills.

------------------------------ Reasonable method ----------------------------

Template auto-loading

To reduce the template loading and calling process and the redundant code of the template, Django provides a convenient and powerful API for loading templates from a disk,

To use this template to load APIs, you must first tell the framework where the template is saved.The saved file is described in the previous chapter.Root_urlconfMentioned During configurationSettings. py.

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.)

This setting tells Django where the template loading mechanism looks for the template. Select a directory to store the template and add itTemplate_dirsMedium:

The most convenient way is to use an absolute path (that is, the directory path starting from the root directory of the file system ). If you want to be more flexible and reduce some negative interference, you can use the Django configuration file as the Python code to dynamically buildTemplate_dirsSuch:

import os.pathTEMPLATE_DIRS = (    os.path.join(os.path.dirname(__file__), ‘templates‘).replace(‘\\‘,‘/‘),)

This example uses the magical Python internal variable_ File __The variable is automatically set to the name of the python module where the code is located. ''OS. Path. dirname (_ file _)'' will get the file where it is located, that isSettings. pyDirectory, and thenOS. Path. JoinIn this methodTemplates. In Windows, it intelligently selects the correct backward slash "" to connect, rather than forward slash "/".

CompleteTemplate_dirsAfter setting, the next step is to modify the view code.

Use the Django template Loading Function instead of hard coding the template path. ReturnCurrent_datetimeView to make the following changes:

from django.template.loader import get_templatefrom django.template import Contextfrom django.http import HttpResponseimport datetimedef current_datetime(request):    now = datetime.datetime.now()    t = get_template(‘current_datetime.html‘)    html = t.render(Context({‘current_date‘: now}))    return HttpResponse(html)

 

In this example, we use the FunctionDjango. template. loader. get_template ()Instead of manually loading templates from the file system. TheGet_template ()The function uses the Template Name as a parameter to locate the module location in the file system, open the file, and return a compiledTemplateObject.

In this example, the template file we selected isCurrent_datetime.html, But this corresponds. HtmlThere is no direct contact with the suffix. You can select any file with any suffix, as long as it is logical. Even selecting a file without a suffix is not a problem.

This page is similar to the error page we have explained in Chapter 3, except that there is an additional debugging information area: the template loader checks the page afterwards. This area shows the template to which Django is loaded and the cause of each attempt error (for example, the file does not exist ). This information is helpful when you try to debug the template loading error.

Next, create the following template code in the template directory:Current_datetime.htmlFile:

Refresh the page in the web browser and you will see the page after the complete resolution.

-------------------------- Other methods ------------------------------------

Render_to_response ()

We have told you how to load a template file and then useContextRender it, and finally return this processedHttpresponseObject to the user. We have optimized the solution and usedGet_template ()The method replaces the complicated code to process the template and its path. However, it still takes some time to extract the simplified code. This is a common repetitive labor. Django provides a shortcut for you to load a template file, render it, and use thisHttpresponse.

This shortcut is locatedDjango. shortcutsThe module name isRender_to_response (). In most cases, you will use it unless your boss measures your work based on the number of lines of code.

------------------- The use of the context processor was originally intended to simplify template rendering ----------------------

Django therefore providesGlobalContext processor support.Template_context_processorsSpecifiedContext ProcessorsAlwaysIt is used by default. In this way, every useRequestcontextAll specifiedProcessors.

By default,Template_context_processorsThe settings are as follows:

TEMPLATE_CONTEXT_PROCESSORS = (    ‘django.core.context_processors.auth‘,    ‘django.core.context_processors.debug‘,    ‘django.core.context_processors.i18n‘,    ‘django.core.context_processors.media‘,)

 

Django -- how to use template and how to pass variables to template

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.