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. Image compression before saving the new model / work with JPG, PNG by Schleidens 5 days, 5 hours ago
  2. Help text hyperlinks by sa2812 1 month ago
  3. Stuff by NixonDash 3 months, 1 week ago
  4. Add custom fields to the built-in Group model by jmoppel 5 months, 1 week ago
  5. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 8 months, 3 weeks 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.