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

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/adsense_tags.py file with the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  1. from django import template
  2. from django.template.loader import render_to_string
  3. register = template.Library()
  4. @register.filter
  5. def inject_adsense_after_paragraph(value, arg):
  6. # Render our adsense code placed in html file
  7. ad_code = render_to_string("app_name/adsense_ads.html")
  8. # Break down content into paragraphs
  9. paragraphs = value.split('</p>')
  10. # Check if paragraph we want to post after exists
  11. if arg < len(paragraphs):
  12. # Append our code before the following paragraph
  13. paragraphs[arg] = ad_code + paragraphs[arg]
  14. # Assemble our text back with injected adsense code
  15. value = '</p>'.join(paragraphs)
  16. 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:

1
2
3
4
5
6
7
8
9
  1. <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
  2. <ins class="adsbygoogle"
  3. style="display:block"
  4. data-ad-client="ca-pub-xxxxxxxxxxx"
  5. data-ad-slot="xxxxxxxxxxx"
  6. data-ad-format="auto"></ins>
  7. <script>
  8. (adsbygoogle = window.adsbygoogle || []).push({});
  9. </script>

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:

1
2
3
4
5
6
7
8
9
  1. {% extends 'base.html' %}
  2. {% load adsense_tags %}
  3. {% block content %}
  4. {% blog.title %}
  5. {% blog.body|inject_adsense_after_paragraph:1 %}
  6. {% 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.