This chapter will teach you the following:

  • Using templates to return more complex html code and variables to templates
  • Mapping the urls to your app

Let’s add some dummy data to pass it to our home page on server using a list of dictionary

Notice, that I am passing the post variable through a dictionary,it could’ve been done in this way too,

Now on our homepage,we want to loop through the posts list,just as we use forloop in python we’ll use templating engine like jinja2 which allows us to write code .

More on creating templates with jinja in python

Notice on line 8 and line 14, You’ll always have to specify the closing tag for every if statement or the forloop.And the variables can be accessed via {{}}.Since we’re looping through a dictionary we’re using . to access the value of the key.Run your server and see the homepage.

On line 5 we’re checking if we have a title variable and if we do then display it in the title tag or else the default is set to ‘DjangoReads’.

Let’s create the about.html file and copy paste all of the from home.html file excluding the forloop to get our about page up and running.

Now,let’s pass a title for about page

Notice we have a lot of similar code in our html files.So let’s put the similar code in one file ,and the unique code in their respective html files.But is it possible to inherit the html code.Well with jinja you can inherit the code too.

To accomplish this, create a new html file ,i’ll call it base.html ,and add to it what’s similar to all your templates.

Notice the block tag,a block is a section that a child template can override. The name after block i.e., body is custom and you can name it whatever you want.You can also add your custom name in the endblock so as to be specific with which block you are closing.

So,now within our home and about template we’ll inherit this template and get all of this information and override the block section in the body tag.The home.html will now look like this,

Make the changes in about.html as we did in home.html file and test the changes by running the server.

Posting Django Tutorials with Beginner to Advanced Projects

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store