Last active
October 1, 2020 23:34
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
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
Replace everything between
<<-MARKUP.strip
andMARKUP
with your own Ad-code.Then just use
{% ads %}
to inject the ads code into the right locations in your post.