Inserting AdSense Ad Codes After Every N Paragraph in Django

Ajay Choudhury 08 Aug, 2021 4 mins
Inserting AdSense Ad Codes After Every N Paragraph in Django

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 customise 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:

  1. (leave this file empty)
  2. (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:

  1. inarticle1.html
  2. inarticle2.html
  3. inarticle3.html
  4. inarticle4.html
  5. inarticle5.html
  6. 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=""
<ins class="adsbygoogle"
     style="display:block; text-align:center;"
     (adsbygoogle = window.adsbygoogle || []).push({});

Similarly, you can bring all of your generated ad codes in different HTML files inside the templates/adsense directory.

<script async src=""

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;"
     (adsbygoogle = window.adsbygoogle || []).push({});

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 file.

from django import template
from django.template.loader import render_to_string

register = template.Library()

def inarticle_ads(value):
    # Render the adsense code placed in html files
    ad_code = []

    # 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 </p> as every paragraph ends with </p> 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:
. . .

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 <p>---This is a Placeholder for Ad---</p>) 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.

Was this Article Helpful?

Ajay Choudhury

Ajay Choudhury

A learner and a student of technlogy. He loves sharing experiences and learning with others through his projects and blog. Along with technology, he loves playing football and enjoys listening to music and podcasts.



Contribute to make this site more awesome →