How to use the python Django template (graphic)

  • 2020-04-02 13:14:01
  • OfStack

Basic introduction to template
A template is a piece of text that separates the presentation and content of a document. Templates define placeholders and various pieces of basic logic (template tags) that govern how the document should be displayed. Templates are commonly used to produce HTML, but Django's templates can also produce any document based on text format.
A project description
1, the establishment of MyDjangoSite project specific not to say, refer to the front.
2. Create a new templates folder in MyDjangoSite.
3. Create the template file user_info.html under the newly created template


<html>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title> The user information </title>
    <head></head>
    <body>
        <h3> User information: </h3>
        <p> Name: {{name}}</p>
        <p> Age: {{age}}</p>
    </body>
</html>

{{name}} is called template variable; {% if xx %}, {% for x in list %} template label.

4. Modify the TEMPLATE_DIRS in settings.py
The import import OS. The path
Add OS. Path. Join (OS) path) dirname (__file__), 'templates'). The replace (' \ \', '/').


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.
    #"E:/workspace/pythonworkspace/MyDjangoSite/MyDjangoSite/templates",
    os.path.join(os.path.dirname(__file__), 'templates').replace('\','/'),
)

Specify the template load path. Where os.path. Dirname (s) is the current settings.py file path, then connect the templates path.

5. New view.py


#vim: set fileencoding=utf-8:
#from django.template.loader import get_template
#from django.template import Context
#from django.http import HttpResponse
from django.shortcuts import render_to_response
def user_info(request):
    name = 'zbw'
    age = 24
    #t = get_template('user_info.html')
    #html = t.render(Context(locals()))
    #return HttpResponse(html)
    return render_to_response('user_info.html',locals())

The basic rules of the Django Template system: write the Template, create the Template object, create the Context, and call the render() method.
You can see the comments section in the code above
#t = get_template('user_info.html') # HTML = t.ender (Context(locals()))
# return an HttpResponse (HTML)
Get_template (' user_info. HTML), django USES the function. The template. Loader. Get_template (), instead of manual loading templates from the file system. The get_template() function takes the Template name as an argument, finds the location of the module in the file system, opens the file, and returns a compiled Template object.
The render(Context(locals()) method receives a set of variable Context passed in. It will return a template-based rendering string, and the variables and tags in the template will be replaced by the context value. Where Context(locals()) is equivalent to Context({'name':' ZBW ','age':24}), and locals() returns a dictionary that maps the names and values of all local variables.
Render_to_response Django provides a shortcut for this, letting you load a template file once, render it, and return it as an HttpResponse.

6. Modify urls.py
 


 from django.conf.urls import patterns, include, url
from MyDjangoSite.views import user_info
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'MyDjangoSite.views.home', name='home'),
    # url(r'^MyDjangoSite/', include('MyDjangoSite.foo.urls')),
    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^u/$',user_info),

)
 

7. Start the development server
Basic a simple template application to complete, start the service to see the effect!
The effect is as follows:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201311/2013110409354815.png ">


Inheritance of templates
Reduces duplication and maintenance costs. Let's look at the application.
New /templates/base.html


<html>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>{% block title %}{% endblock %}</title>
    <head></head>
    <body>
        <h3>{% block headTitle %}{% endblock %}</h3>
        {% block content %} {% endblock %}
        {% block footer %}
            <h3> Hey, this is an inherited template </h3>
        {% endblock%}
    </body>
</html>

2. Modify /template/user_info.html and create product_info.html
Urser_info. HTML

{% extends "base.html" %}
{% block title %} The user information {% endblock %}

<h3>{% block headTitle %} User information: {% endblock %}</h3>
{% block content %}
<p> Name: {{name}}</p>
<p> Age: {{age}}</p>
{% endblock %}

Product_info. HTML

{% extends "base.html" %}
{% block title %} Product information {% endblock %}
<h3>{% block headTitle %} Product information: {% endblock %}</h3>
{% block content %}
    {{productName}}
{% endblock %}

3. Write view logic and modify views. Py

#vim: set fileencoding=utf-8:
#from django.template.loader import get_template
#from django.template import Context
#from django.http import HttpResponse
from django.shortcuts import render_to_response
def user_info(request):
    name = 'zbw'
    age = 24
    #t = get_template('user_info.html')
    #html = t.render(Context(locals()))
    #return HttpResponse(html)
    return render_to_response('user_info.html',locals())
def product_info(request):
    productName = ' Amoxicillin capsules '
    return render_to_response('product_info.html',{'productName':productName})

4. Modify urls.py


from django.conf.urls import patterns, include, url
from MyDjangoSite.views import user_info,product_info
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'MyDjangoSite.views.home', name='home'),
    # url(r'^MyDjangoSite/', include('MyDjangoSite.foo.urls')),
    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^u/$',user_info),
    url(r'^p/$',product_info),
)

5. The service effect is as follows:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201311/2013110409354816.png ">


Related articles: