Login

Tweet embed template tag

Author:
z3ke1r
Posted:
February 14, 2019
Language:
Python
Version:
2.1
Score:
0 (after 0 ratings)

Takes a tweet url, requests the json from Twitter oEmbed, parses the json for the html element and returns it to your template. The html returned is ready to go and will be shown as a tweet on your web page. This uses the Requests library for Python. A full example can be found on GitHub https://github.com/z3ke1r/django-tweet-embed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import requests
from django import template

register = template.Library()

@register.simple_tag
def tweet_tags(url):
    twtjson = requests.get('https://publish.twitter.com/oembed?url=' + url + '&omit_script=true')
    twtparse = twtjson.json()
    twthtml = twtparse['html']
return twthtml

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

z3ke1r (on February 15, 2019):

Example:

This will loop through the 'tweets' queryset (defined in the view). Send the URL of each tweet object (x) to the tag function and return the embed HTML into the <div card> in the template.

template.html

{% load tweet_tags %}


{% for x in tweets %}
    <div class="mdl-card__media">
        {% autoescape off %}{% tweet_tags x.url %}{% endautoescape %}
        <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
    </div>
{% endfor %}

#

Please login first before commenting.