Let's Learn Django #4 Using templates & static files
Tags: python, django, webdev, beginners
Published: 2023-06-17 10:51:09

We have already seen how to write our first view in the previous blogs. In this blog, we will explore how to use & render templates.

### What are templates?

Templates are simply HTML files that we can render as a response to a URL/view.  
Django templates offer a robust templating language with various built-in tags and filters that you can utilize to manipulate and display data in your HTML templates.  
We will explore it in detail in the next blog

### Setting up templates folder

Setting up a templates folder is quite easy. First, we will create a new folder in the base directory with the name `templates`.  
Next, we need to tell Django that we will be using this folder for placing all our templates.

For that, we all navigate to our settings.py file. There is a list named `TEMPLATES` & it will have a JSON object with a field named `DIRS` that contain an empty list. We just need to add `templates` (the name of our folder) to it.  
Finally, it should look something like this:  

```python
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
```

That is all we need to do to set up templates.  
Now we will see how to use templates.

### Rendering templates

Rendering a template means generating an HTML response that incorporates the dynamic data and logic defined in your views, which is then sent to the user's browser.

In the last blog, we saw how to write our views. So now, let's render an HTML template as a response to that view.  
First, we will create a new HTML file in the templates directory with the name `hello.html`  
You can then add any HTML page design you want.  
I will go with a simple one.  

```xml
<!DOCTYPE html>
<html>
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <h1>Hello World!</h1>
        <p>My name is <strong>Rachit Khurana</strong></p>
    </body>
</html>
```

Now, we will return this template when the user goes to the index page.  
For that, we will navigate to `views.py` where we defined a hello function that gets called when the user goes to the index page.  
We will then use `render` function from `django.shortcuts` to render this template.  
The `render` function simplifies the process of rendering templates by handling the template loading and rendering process automatically. It takes the request, the template file path, and an optional context as arguments and returns an HTTP response with the rendered template.

The `views.py` code will look like this

```python
from django.shortcuts import render, HttpResponse

# Create your views here.
def hello(request):
    return render(request, 'hello.html')
```

Now if we run the server & go to [http://127.0.0.1:8000/](http://127.0.0.1:8000/), we will be able to see this as an HTML-rendered page. Awesome right?  
  
However, do note that you won't be able to create CSS or JS files in the templates folder & use those in the HTML file.  
This is because Django only takes the HTML file, & returns the rendered file directly. It doesn't take the CSS & JS files. To use separate CSS & JS files, we need to serve them as static files.  
We will now see how to serve static files.

## Static Files

Static files include CSS, JavaScript, images, and other files that remain constant for all users visiting your website. These files are served directly to the client's browser and contribute to the visual and interactive aspects of your web pages.  
  
To set up static files, we will create a new folder named `static`.  
Now we need to tell Django to use this folder for serving static files. For that, we will add the following line to the `settings.py` file:

```python
STATICFILES_DIRS = [
    BASE_DIR / "static"
]
```

`STATICFILES_DIRS` is a list where you specify the directory paths where Django should look for static files.

That's it. Now whatever file we store in the static folder will be available at http://127.0.0.1:8000/static/&lt;filename&gt;.  

### Using static files inside templates

Now, let's create a simple CSS file with the name `style.css`. I will be using a pretty simple CSS file for demonstration.

```css
body{
    background-color: #ca1c1c;
    color: aqua;
}
```

Now, we will use this in our `hello.html` file by making use of the static tag. First, we will import it & then use it as shown below:

```xml
{% load static %}
<!DOCTYPE html>
<html>
    <head>
        <title>Hello World!</title>
        <link rel="stylesheet" href="{% static 'style.css' %}">
    </head>
    <body>
        <h1>Hello World!</h1>
        <p>My name is <strong>Rachit Khurana</strong></p>
    </body>
</html>
```

  
Now when we run the server & go to [http://127.0.0.1:8000/](http://127.0.0.1:8000/) we will see the new HTML page with the CSS.


![homepage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ic6jwu44o7ekl9b8v3am.png)



Congratulations, you know know how to render an HTML template & use static files. But what if we need to pass an argument from the code to the template?  
We can also do that easily. Let's take a look at how to do that.

### Passing arguments to the template

We can easily pass variables to the template to render.  
For eg, I want to pass my name & age to the template. We will go to the `views.py` file & declare these variables in the function.  
We then need to pass another argument to the render function with all the variables we need to pass to the template as a dictionary.  
The final code will look like this:

```python
from django.shortcuts import render, HttpResponse

# Create your views here.
def hello(request):
    name="Rachit Khurana"
    age=19
    return render(request, 'hello.html', {'name':name, 'age':age})
```

Now we can use these variables in the template `hello.html` by wrapping them with double curly brackets like this:

```xml
{% load static %}
<!DOCTYPE html>
<html>
    <head>
        <title>Hello World!</title>
        <link rel="stylesheet" href="{% static 'style.css' %}">
    </head>
    <body>
        <h1>Hello World!</h1>
        <p>My name is <strong>{{name}}</strong></p>
        <p>My age is <strong>{{age}}</strong></p>
    </body>
</html>
```

Here `{{name}}` will get replaced by the value of `name` we have passed to the template. Now if we try to run the server & go to [http://127.0.0.1:8000/](http://127.0.0.1:8000/) we can see the new rendered HTML page with those variables.

Like this:


![homepage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c0ggpdbt8n0kolmqg11b.png)



We can not only pass string or int values, but we can also pass lists, tuples, dictionaries etc.  
  
Congratulations, you now know how to render templates, serve static files & pass variables to the template. But that's not all, Django templating is way more powerful than this. We will explore more about it in the next blog.