Skip to content

Django Templating

sachin soman edited this page Jun 8, 2020 · 5 revisions

Templates

Directories

Django also follows templating rules like flask jinja2 templating methods. However, there are some notable differences. The first is in the structuring of the directories. Django looks at each app for templates. So for us, we will need to create a templates directory in our app directory and in that directory, we will again need to have a directory with the name of our project; since in our Django project we had an app called blog, we will inside the templates another directory called blog a bit unconventional. Screenshot 2020-06-08 at 18 08 18
So now its django_project/blog/template/blog Now inside that, we can create HTML files which can be used in templating

Adding template Config

Now that we have created the directories and HTML files we need to tell Django to search for these templates for that first go to blog apps app.py file in that we will see a class in our case it is BlogConfig copy that. Now go to the settings.py file in the project directory go to INSTALLED_APPS and add blog.apps.BlogConfig.

Loading the template

Now that Django knows where to look for the template we can use the render function to serve the template. Unlike flask Django serve function is imported from from django.shortcuts import render

Now to do the render we write return render(request,'directoryname/html_page.html') we can have a third argument as well which will be the data which we can pass return render(request,'directoryname/html_page.html',data). And use it access data via templates.

Templating Engine syntax