Django TemplatesDjango provides a convenient way to generate dynamic HTML pages by using its template system. A template consists of static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted. Why Django Template?In HTML file, we can't write python code because the code is only interpreted by python interpreter not the browser. We know that HTML is a static markup language, while Python is a dynamic programming language. Django template engine is used to separate the design from the python code and allows us to build dynamic web pages. Django Template ConfigurationTo configure the template system, we have to provide some entries in settings.py file. Here, we mentioned that our template directory name is templates. By default, DjangoTemplates looks for a templates subdirectory in each of the INSTALLED_APPS. Django Template Simple ExampleFirst, create a directory templates inside the project app as we did below. After that create a template index.html inside the created folder. Our template index.html contains the following code. // index.html Loading TemplateTo load the template, call get_template() method as we did below and pass template name. //views.py Set a URL to access the template from the browser. //urls.py Register app inside the INSTALLED_APPS Run ServerExecute the following command and access the template by entering localhost:8000/index at the browser. Django Template LanguageDjango template uses its own syntax to deal with variable, tags, expressions etc. A template is rendered with a context which is used to get value at a web page. See the examples. VariablesVariables associated with a context can be accessed by {{}} (double curly braces). For example, a variable name value is rahul. Then the following statement will replace name with its value. Django Variable Example//views.py //index.html Output: TagsIn a template, Tags provide arbitrary logic in the rendering process. For example, a tag can output content, serve as a control structure e.g. an "if" statement or a "for" loop, grab content from a database etc. Tags are surrounded by {% %} braces. For example. Next TopicURL Mapping |