Creating Custom Template Filter That Injects Adsense Ad Code After N Paragraph in Django

Jun 30, 2015 · by Tim Kamanin

Injecting ads inside content is a very effective technique. Let's say you want to inject Adsense ad after the first paragraph of text. To add such capability to our Django-based website we need to create a custom filter for that. I'll tell you how to implement such a filter.

1) In your app, create a templatetags/ file with the following code:

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

register = template.Library()

def inject_adsense_after_paragraph(value, arg):

# Render our adsense code placed in html file
ad_code = render_to_string("app_name/adsense_ads.html")

# Break down content into paragraphs
paragraphs = value.split('</p>')

# Check if paragraph we want to post after exists
if arg < len(paragraphs):

# Append our code before the following paragraph
paragraphs[arg] = ad_code + paragraphs[arg]

# Assemble our text back with injected adsense code
value = '</p>'.join(paragraphs)

return value

2) Then you need to put your Adsense code into the app_name/adsense_ads.html file, you may have something like this:

<script async src="//"></script>
<ins class="adsbygoogle"
(adsbygoogle = window.adsbygoogle || []).push({});

3) In the end, let's use our filter on content, let's say your blog post has a following template blog/blogpost_detail.html:

{% extends 'base.html' %}
{% load adsense_tags %}

{% block content %}

  {% blog.title %}
  {% blog.body|inject_adsense_after_paragraph:1 %}

{% endblock content %}

As you see, all we need to do is to add filter inject_adsense_after_paragraph to our blog body and pass number of the paragraph after which we want to show the ad. In our case, we want to display the add after the first paragraph of text.

Want to get more 🔥 tips like this one?

Subscribe to get notified about new dev tutorials