The premise behind a template language is that the language is “embedded” within some other master document. It is a language that allows for the definition of placeholders that are going to be replaced later on in the design process. Templates allow for the definition of placeholders that will later be filled in and replaced with actual content. There is a wide range of capabilities that come packaged as a part of most modern, web-based templating languages. It’s possible, for instance, to loop through information and provide conditional logic within a template!
Mako is one such templating language that is designed to maximize both performance and simplicity of syntax. One main feature of Mako is that it provides familiarity with other templating languages, but makes improvements upon them to make the resulting code as readable as possible. Mako also allows you to write Python logic inside the templates, making it one of the best-designed templating languages today. In this article, we will look at how we can Integrate Mako with Django and also look at some of the errors people run into while doing so.
Installation and Setup
Let’s start and create the Django project and after that, we will adjust it for mako templates. First, install the following prerequisites to proceed further:
pip install djangomako
The next step is to create a Django project and an example app:
django-admin startproject makoprojectcd makoproject
python manage.py startapp makoapp
Now we can adjust our settings backend for using Mako; writing a custom backend is fairly simple. We need one class inheriting our BaseEngine that will return Template objects within it. Inside these Template classes, we’ll have control over the logic and rendering of content, just the way we want it.
First, add ‘djangomako’ and your app’s name to the installed apps list:
# settings.py
INSTALLED_APPS = [
# ...
'djangomako',
'makoApp',
]
Then add the code given below to the very bottom of the templates section:
# settings.py
import os
TEMPLATES = [ # ...
{
'BACKEND': 'djangomako.backends.MakoBackend',
'NAME': 'mako',
'DIRS': [
os.path.join(BASE_DIR, 'templates')
],
},]
The next step is to adjust the djangomako package for our project because it has the old import to the static files. To fix it, we must find our package djangomako, an easy way to do this is to start the project server with: ‘python manage.py runserver’ and it will throw an error, in one of those lines there will be the location of the file named ‘backend.py’. This would look something like this:
This is where the wrong import is situated at. This file’s location is different for everyone’s system so you have to navigate there yourself, or, if you are using VScode you can also just cltr + click on the location line and it will open the file.
Now, on the backends.py file go to line 14, as suggested in the picture above, and change that line with the one given below:
#Old import
from django.contrib.staticfiles.templatetags.staticfiles import static
#New import from django.templatetags.static import static
After that, on the same file, if you are getting an error on line 204, delete that line and replace it with the following one:
#Old import
from django.core.urlresolvers import reverse
#New import
from django.urls import reverse
Now as a final check to see if everything worked or not run the server again:
python3 manage.py runserver #Linux/Mac
python manage.py runserver #Windows
When we start our local server now, everything will go smoothly. And with this information in mind, If you want to have full control over this package, you can also create a folder with an init file in the root directory. Copy backends.py into it and it will work as a Python module!
Next up, set up the URLs in the makoproject/urls.py file:
# makoproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('makoApp.urls'))
]
Using the library
And now we can finally start using the Mako library in our application, but first, we’ll have to set up the URLs for it. To do that create a file called urls.py inside your application’s directory (makoapp), and then paste the following lines into it:
# makoapp/urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('', MakoView.as_view(), name='home'),
]
Then, open the views.py file and add the following code to it; this is a simple function just to show some predefined names, although it could be also routed through the models or forms.
# views.py
from django.shortcuts import render
from django.views.generic import TemplateView #get the mako template to views
class MakoView(TemplateView):
template_name = "home.mako" #define the template name
def get_context_data(self, **kwargs):
context = super(MakoView, self).get_context_data(**kwargs) #get the makoview to the thempltes
context.update({
'names': [
'User',
],
})
return context
Last but not least is to make sure we create a templates directory at the root level of our project and create a ‘home.mako’ file within it (although you can also use the .html extension). After that you can paste the following code into it:
#templates/home.mako
#Example to showcase the view function
<p>Welcome to mako template</p>
<ul>
% for name in names:
<li>${ name }</li>
% endfor
</ul>
#Example to show Mako's integrated capablities
<%
from random import randint
numbers = [randint(1,10) for _ in range(10)]
%>
<ul>
% for n in numbers:
<li>${n}</li>
% endfor
</ul>
And we are all done!
As you can see, the first example will render out the function that we created in the views, which is to render the predefined name. But this is nothing special, DTL could also do it.
But if you see in the second example, there is arbitrary Python code written in the template. It is a simple program to print out 10 random numbers and it will render to the template through the HTML tag <li>.
Results
Now after doing all the steps given above, you will be ready to start the Django development web server to view your results. You can start the server using the following command:
python3 manage.py runserver #Linux/Mac
python manage.py runserver #Windows
If the server started successfully, visit the link given which would be this http://127.0.0.1:8000/. And If everything worked fine, you would see a page something like this:
Conclusion
Mako is easy to learn, but it’s also an extremely powerful template engine. It can unleash the full power of Django to create dynamic, rich content pages. But there are some things that you have to learn to use it, such as the tags. But considering all the features it offers is enough to get a lot of people starting to use it.
In this article, we have looked at how we can Integrate Mako with Django and also look at some of the errors people run into while doing so. We hope that this article helped you integrate Mako with Django. If you have any other questions or concerns about this topic, please contact us anytime. If you are looking for a templating language to use for your next project, we recommend that you take a look at Mako.