Skip to content
thesarfo

Note

Using Templates in Django

Rendering HTML templates with render(), passing a context dictionary, and using Jinja-style conditionals in a template.

views 0

Let’s see how we can use a template to return HTML content to a client/browser. In your app’s directory, add a new folder called “templates”. And in the templates folder create a file called “hello.html”.

You can add HTML content you wanna render, in the above created file.

Now head back to the views.py file. Instead of our view function return plain strings or HTML to the browser, we use the “render” keyword/function instead. The render function takes two parameters. The first one is a request object, that is the request parameter that we passed to our above function. The second one is the name of the html file to be rendered, which is a string. See below.

def say_hello(request):
return render(request, 'hello.html')

Now when we make these changes in our views.py file, we render the “hello.html” file into our browser.

Now we can dynamically render data into our template file as well. For example a variable. The third parameter that the render function takes is a dictionary which contains things we want to render in the specified template.

For instance, I want to render the name ‘Ernest’ into the browser. We can add a third parameter to the render function and inside the dictionary, give it a key and a value. See below

def say_hello(request):
return render(request, 'hello.html', {name: "Ernest"})

Now in our template file, we can render the name “Ernest” by putting the dictionary key inside curly braces. See below.

<h1>Hello {{ name }}</h1>

This will render the value of the name key inside our dictionary. Hence, “Hello Ernest”.

We can also write logic inside our templates. For example if we want to write an if statement, we use curly braces and percentage symbols. {% if condition here %}. See below

{% if name %}
<h1>Hello {{ name }}</h1>
{% else %}
<h1>Hello World</h1>
{% endif %}