Maybe you want to customize and extend the template engine. The following describes how to extend the template system and how the template system works, the auto-escapint function in the Django template system is also introduced, which is a security mechanism. Review Template language usage # template tag usage # }{% if done % }< strong> Over </strong>
{% Else %} <strong> wait </strong> {% endif %} {# template variable usage #} Now is {nowtime} in views. when using the template in py: 1. obtain the template object using the Template Name. 2. create a context object, similar to a dictionary, used to provide the actual value of the variable like a template 3. when the context object is used for template rendering, the returned html webpage content is reused using RequestContext. When rendering a template, we usually use django. template. the Context object. Here we will introduce another sub-class, django. template. requestContext and RequestContext provide a method to extract the public parts of different context content and reuse the content of context. Example 1: Context
FromDjango. template
ImportLoader, Context
FromDjango. http
ImportHttpResponse
DefView_1 (request ):
#...
T = loader.get_template('template1.html ')
C = Context ({
'App': 'My app ',
'User': request. user,
'IP _ address': request. META ['remote _ add'],
'Message': 'I am view 1 .'
})
ReturnHttpResponse (t. render (c ))
DefView_2 (request ):
#...
T = loader.get_template('template2.html ')
C = Context ({
'App': 'My app ',
'User': request. user,
'IP _ address': request. META ['remote _ add'],
'Message': 'I am the second view .'
})
ReturnHttpResponse (t. render (c ))
We can see that some of the two contexts are duplicated. For example, app, user, ip_address
2. Rewrite it to RequestContext
FromDjango. template
ImportLoader, RequestContext
FromDjango. http
ImportHttpResponse
# Use context processro to provide some public parts of the context content, that is, to return a dictionary.
DefCustom_proc (request ):
"A context processor that provides 'app', 'USER' and 'IP _ address '."
Return{
'App': 'My app ',
'User': request. user,
'IP _ address': request. META ['remote _ add']
}
DefView_1 (request ):
#...
T = loader.get_template('template1.html ')
# The creation method is different. Three parameters are required: request object, Dictionary type, and processors. Optional.
C = RequestContext (request, {'message': 'I am view 1 .'},
Processors = [custom_proc])
ReturnHttpResponse (t. render (c ))
DefView_2 (request ):
#...
T = loader.get_template('template2.html ')
C = RequestContext (request, {'message': 'I am the second view .'},
Processors = [custom_proc])
ReturnHttpResponse (t. render (c) can see that the so-called context processors is actually a function, the parameter is request, and a dictionary type is returned. This is what it does. Here, custom_proc returns the dictionary that contains the three common parameters. The third parameter processors in the RequestContext constructor is optional. It can be a list of multiple custom_proc functions or tuples, here we only pass one or more. Use the render_to_response function in combination with RequestContext to directly return the HttpResponse objectReturnRender_to_response('template2.html ',
{'Message': 'I am the second view .'},
Context_instance = RequestContext (request, processors = [custom_proc])
The above code can be put in place in one step.
However, another problem is introduced. Every time you use the render_to_response function, you must specify the required context processors to RequestContext. For this reason, Django provides global processors, it is passed to the RequestContext object by default. This setting corresponds to the TEMPLATE_CONTEXT_PROCESSORS attribute in the D: \ Python27 \ Lib \ site-packages \ django \ conf \ global_setings.py file, in this way, you do not need to specify processors each time you use RequestContext. I am using Django-1.4 now, so the path is here, it seems that the previous version is directly under the project folder settings. py file, which is represented by strings of some processors functions. The following describes some common parameters provided by processors that are opened by default:
- Django. contrib. auth. context_processors.auth
User: the username perms for the current Logon: All permissions of the user.
- Django. core. context_processors.debug
Debug: whether to enable the DEBUG mode SQL _queries: {'SQL ':..., 'time ':...} it displays the time required for executing each SQL query and its execution. From the Django source code, we can see that to use this processors, you must first enable the debugging mode, and then your IP address must be in the INITERNAL_IPS tuples. What is INITERNAL_IPS? It is an empty tuples in the previous global_settings.py file and should be used for Security Authentication Settings (speculation ).
- Django. core. context_processors.request
This is the processors of the request object. It is estimated that the request object is directly returned. The source code is the same as imagined. Some suggestions for customizing global processors: 1. make sure that each processor corresponds to only a small part of the data required by the function, so as to ensure higher reusability, more combinations, not too repetitive. 2. once the global processor is defined, it will be visible to all template files using RequestContext. Therefore, pay attention to the selection of template variable names, one better way is to use uppercase letters for all the variables in the global processor. 3. I used to put the processors function in the file named context_processors.py. You can write your path in the TEMPLATE_CONTEXT_PROCESSORS tuples.
Publish by note