Skip to content

Instantly share code, notes, and snippets.

@sverrirs
Last active October 1, 2020 23:34
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sverrirs/633190aa06ea7d7e7f3a to your computer and use it in GitHub Desktop.
Save sverrirs/633190aa06ea7d7e7f3a to your computer and use it in GitHub Desktop.
How to create a Jekyll custom tag that injects Google Ads into posts
# http://www.createdbypete.com/articles/create-a-custom-liquid-tag-as-a-jekyll-plugin/
class AdsInlineTag < Liquid::Tag
def initialize(tag_name, input, tokens)
super
@input = input
end
def lookup(context, name)
lookup = context
name.split(".").each { |value| lookup = lookup[value] }
lookup
end
def render(context)
<<-MARKUP.strip
<div style="width: 728px; margin: 0 auto; padding: .8em 0;">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-2754843202551236" data-ad-slot="2662611504" data-ad-format="auto"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script></div>
MARKUP
end
def split_params(params)
params.split("|")
end
end
Liquid::Template.register_tag('ads', AdsInlineTag)
@sverrirs
Copy link
Author

Replace everything between <<-MARKUP.strip and MARKUP with your own Ad-code.

Then just use {% ads %} to inject the ads code into the right locations in your post.

@vijayparikh
Copy link

Hi - you might want to modify the render method as follows:

  def render(context)
    source = <<-MARKUP.strip
    <div style="width: 728px; margin: 0 auto; padding: .8em 0;">
      <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
        <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-2754843202551236" data-ad-slot="2662611504" data-ad-format="auto"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script></div>
    MARKUP
    source = TemplateWrapper::safe_wrap(source)
  end

I was having an issue with the add showing up as a text being formatted by RDiscount - TemplateWrapper::safe_wrap prevents this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment