Placing AdSense codes in the right places can be effective and can yield good results when done with the right content. We can place AdSense ad codes on any of our eligible content on websites or blogs. Django is not an exception and we can place our ad codes very effectively on sites built with Django using the power of Python.
Most of the time, AdSense auto ads can handle the task quite efficiently but those who want better, clean and precise placement of ads can always customize or mention specific places for ads. To place ad codes between content, we will need a custom Django template filter which we will be creating below.
The custom template filter we are going to design can insert different AdSense ad codes after every Nth paragraph of the content in a Django blog/website.
Creating required files and Ads
First of all, let me specify all the files we need to create to achieve our goal. We will be creating 6 different In article ad codes from AdSense. Also, I assume you already have a Django app inside your project named blog (it might be different but, we will consider it as blog in this guide), and you should have your templates folder ready.
Now, inside the app blog, create a folder named templatetags
inside which we will create two files namely:
-
__init__.py
(leave this file empty) - ad_filter.py (we will create our filter here)
Now, go to the templates folder and create a subfolder named adsense, inside the subfolder, we will keep our AdSense ad codes in
.html
files and hence we will create our six different.html
files namely: - inarticle1.html
- inarticle2.html
- inarticle3.html
- inarticle4.html
- inarticle5.html
- inarticle6.html Inside each of the HTML files we created just now, we will paste different ad codes generated from AdSense, for e.g.
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-your_adsense_id"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-your_adsense_id"
data-ad-slot="unique_code"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
Similarly, you can bring all of your generated ad codes in different HTML files inside the templates/adsense directory.
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-your_adsense_id"
crossorigin="anonymous"></script>
Note that, if you have already put the above in the head of your base template or anywhere else once, then you need not put those again on every ad code (by default it is included but you should remove the redundant codes). For e.g., if you have pasted the content in inarticle1.html like shown above then from the next file onwards, you can just put ad codes like:
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-your-adsense-id"
data-ad-slot="unique_code"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
Designing the template filter
We now have our ad codes with us, we need a filter to place them accordingly. First of all, we will import the required module for reading the HTML files containing the ad codes. After that, we will define and register our template filter inside the ad_filter.py file.
from django import template
from django.template.loader import render_to_string
register = template.Library()
@register.filter
def inarticle_ads(value):
# Render the adsense code placed in html files
ad_code = []
ad_code.append(render_to_string("adsense/inarticle1.html"))
ad_code.append(render_to_string("adsense/inarticle2.html"))
ad_code.append(render_to_string("adsense/inarticle3.html"))
ad_code.append(render_to_string("adsense/inarticle4.html"))
ad_code.append(render_to_string("adsense/inarticle5.html"))
ad_code.append(render_to_string("adsense/inarticle6.html"))
# set adcode picker
j = 0
# Break down content into paragraphs
paragraphs = value.split("</p>")
# insert after every 5th paragraph
for i in range(len(paragraphs)):
if i % 5 == 0:
paragraphs[i] = paragraphs[i] + ad_code[j]
if j < 5:
j += 1
value = "</p>".join(paragraphs)
return value
In the function inarticle_ads() above, I have first read all the ad codes and appended them to a list as strings. Next, I have split the content by
as every paragraph ends with tag, here we will get the total number of paragraphs. Now, we will run a for-loop till the last paragraph and insert ad codes only after every 5th paragraph including the 0th paragraph (you can exclude the 0th paragraph if you like with a simple if statement as shown below).. . .
if i % 5 == 0:
if i == 0:
continue
. . .
To add the ad codes to the paragraph, I have simply used the split() function on paragraphs and then added the ad codes after them after which I have considered the whole as a single entity. This process is repeated till the last paragraph, after which we obtain a single entity i.e. our content but with ad codes placed after every 5th paragraph.
Now, to get different ad codes we have used another variable j and used that to iterate across different codes in the list ad_code and we have updated the variable j only when we use the ad code and until we reach our last ad code (here 5th code in the list starting from 0).
Using the template filter on our content
Now to use the template filter we just created, go to your blogpost template that contains the content and use the filter as shown below:
{% extends 'base.html' %}
{% load ad_filter %}
{% block body %}
{% blog.title %}
{% blog.thumbnail %}
{% blog.body|inarticle_ads|safe %}
{% endblock body %}
Check your page now, you should see your ads live at desirable positions. If you are in the development environment you can use simple HTML codes instead of ad codes (like
---This is a Placeholder for Ad---
) to test the working of the template filter.I Hope, the guide helped you achieve what you thought of. Thanks to Tim Kamanin for the starting idea. If you find it useful, kindly share it with others and like the article on my blog.
Top comments (0)