Create Share buttons using Django Templatetags
Download TemplateIt's easy to copy and paste urls to share links, but its easier to just click on a button to do it.
%{--- %{project_name}%/%{application_name}%/templatetags/sharebuttons.py ---}%
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):
try:
# 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):
try:
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}%
share_url=""
if self.service_string =="twitter":
share_url='<a href="http://twitter.com/home?status=%s %s">twitter</a>' %(object_name + " template", object_url)
if self.service_string =="facebook":
share_url='<a href="http://www.facebook.com/sharer.php?u=%s&t=%s">facebook</a>' %(object_url,object_name)
if self.service_string =="linkedin":
share_url='<a href="http://www.linkedin.com/shareArticle?mini=true&url=%s&title=%s">linkedin</a>' %(object_url, object_name)
return share_url
except:
pass
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.
