django template syntax learning include example in detail

  • 2020-06-15 09:46:23
  • OfStack

preface

In many websites, there is basically a beginning and an end, which is displayed on every page. In contrast to this, in Django, the best approach is to use the include tag, adding the start and end tags to each template.

include tags are used

Suppose we have the following template index.html, the code is:


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
<div> The public header section of the web page </div>
<h2>  Web page body Part of the  </h2>
<div> The public bottom section of the web page </div>
</body>
</html>

Children's shoes developed by web know that the common head of most web pages and the common bottom part of the code are one for each page, so it should be taken out separately as an html. When modifying this part of the code, there is no need to modify each page, so we can do this in django:

top.html


<div> The public header section of the web page </div> 

bottom.html


<div> The public bottom section of the web page </div> 

index.html


<!DOCTYPE html> 
<html lang="en"> 
<head> 
 <meta charset="UTF-8"> 
 <title>Title</title> 
</head> 
<body> 
{% include 'top.html' %} 
<h2>  Web page body Part of the  </h2> 
{% include 'bottom.html' %} 
</body> 
</html>

We can use the Include syntax of the django template engine to include individual pages in the current template page. If you have a question, can the context that we pass to the template through the view be used in the included template? You can use it directly.

Suppose we have the following view:


def index(request): 
 return render(request, 'index.html', {'a': 100, 'b': 200}) 

This django view function is passed to the template and rendered to the template.

top.html is amended as follows:


<div> Public header section: {{ a }}</div> 

There is no problem with using it this way.

I have a question like this, if all the pages use the common head top.html, it may be for 1.html 2.html 3.html to use some of the head style is not the same, required ES54en.html:


<div classs='acss'> The public header section of the web page </div> 

However, for 5.html and 6.ES60en, the header style used is:


<div class='bcss'> The public header section of the web page </div> 

Obviously, including public headers directly via include can cause some page display problems. Since some of the parameters are not the same, include allows us to pass parameters to the template that is include, we can use the with syntax, and the problem is solved as follows:


{{ % include 'top.html' with mycss='acss' % }} 

top.html may be modified as follows:


<div class='{{mycss}}'> The public header section of the web page </div> 

Some parameters in the template are included and dynamically specified by include, so that top.html does not have to write multiple pieces of code for nuance.

conclusion


Related articles: