Create Share buttons using Django Templatetags

Download Template
It's easy to copy and paste urls to share links, but its easier to just click on a button to do it.

February 16, 2012

%{--- %{project_name}%/%{application_name}%/templatetags/ ---}%

from django.template import Library, Node
from %{project_name}%.%{application_name}%.models import %{model_to_share}%
from django import template

register = template.Library()
def do_share_buttons(parser, token):
        # split_contents() knows not to split quoted strings.
        tag_name, context_obj, service_string = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
    if not (service_string[0] == service_string[-1] and service_string[0] in ('"', "'")):
        raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
    return ShareButtonNode(context_obj, service_string[1:-1])

from django import template
class ShareButtonNode(template.Node):
    def __init__(self, context_obj,service_string):
        self.service_string = service_string
        self.context_obj = template.Variable(context_obj)

    def render(self, context):
           actual_object = self.context_obj.resolve(context)

	   #model needs to have get_absolute_url function
           object_url = actual_object.get_absolute_url()
           object_name = actual_object.%{model_name_field}%

           if self.service_string =="twitter":
              share_url='<a href=" %s">twitter</a>' %(object_name + " template", object_url)
           if self.service_string =="facebook":
              share_url='<a href="">facebook</a>' %(object_url,object_name)
           if self.service_string =="linkedin":
              share_url='<a href="">linkedin</a>' %(object_url, object_name)

           return share_url

def render(self, context):
    new_context = Context({'var': obj}, autoescape=context.autoescape)

register.tag('sharebutton', do_share_buttons)

%{--- usage in a template ---}%
<h1>share button test</h1>
{% load sharebuttons %}

{% for p in posts %}
   {% sharebutton p "twitter" %}<br />
   {% sharebutton p "facebook" %}<br />
   {% sharebutton p "linkedin" %}<br />
{% endfor %}

You must be logged in to comment.