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. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 2 months, 4 weeks ago
  2. Python Django CRUD Example Tutorial by tuts_station 3 months, 2 weeks ago
  3. Browser-native date input field by kytta 4 months, 4 weeks ago
  4. Generate and render HTML Table by LLyaudet 5 months, 1 week ago
  5. My firs Snippets by GutemaG 5 months, 1 week 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.