Skip to content

Instantly share code, notes, and snippets.

@allenheltondev
Created December 11, 2024 12:55
Show Gist options
  • Save allenheltondev/0997e8b568d857f99179bc867d105f45 to your computer and use it in GitHub Desktop.
Save allenheltondev/0997e8b568d857f99179bc867d105f45 to your computer and use it in GitHub Desktop.
Hugo shortcode for LinkedIn, Twitter/X, and Bluesky posts
<!-- Examples -->
<!-- {{<social url="https://www.linkedin.com/embed/feed/update/urn:li:share:7272370437869703168">}} -->
<!-- {{<social url="https://x.com/AllenHeltonDev/status/1866616019583664459">}} -->
<!-- {{<social url="https://bsky.app/profile/readysetcloud.io/post/3lcvejggsos26">}} -->
{{- $url := .Get "url" -}}
{{- if not $url -}}
{{- errorf "'url' is a required field." -}}
{{- end -}}
{{- $width := or (.Get "width") "504" -}}
{{- $height := or (.Get "height") "600" -}}
{{- define "fetchOEmbedHTML" -}}
{{- $req := . -}}
{{- with resources.GetRemote $req -}}
{{- with .Err }}
{{- errorf "Error fetching oEmbed from %s: %s" $req . -}}
{{- else }}
{{- $data := transform.Unmarshal (.) -}}
{{- $data.html | safeHTML -}}
{{- end }}
{{- else }}
{{- warnf "Unable to retrieve oEmbed data from %s" $req }}
{{- end }}
{{- end -}}
{{- if or (in $url "twitter.com") (in $url "x.com") -}}
{{- $parts := split $url "/" -}}
{{- if lt (len $parts) 6 -}}
{{- errorf "Invalid Twitter/X URL." -}}
{{- end -}}
{{- $user := index $parts 3 }}
{{- $status := index $parts 4 }}
{{- $tweetid := index $parts 5 }}
{{- if ne $status "status" -}}
{{- errorf "Invalid Twitter/X url. Missing 'status' path." -}}
{{- end -}}
{{- if not $tweetid -}}
{{- errorf "Invalid Twitter/X URL. Missing tweet id." -}}
{{- end -}}
{{- $query := querify "url" (printf "https://twitter.com/%s/status/%s" $user $tweetid) -}}
{{- $oembedUrl := printf "https://publish.twitter.com/oembed?%s" $query -}}
{{ template "fetchOEmbedHTML" $oembedUrl }}
{{- else if in $url "bsky.app" -}}
{{- $params := dict "url" $url "format" "json" -}}
{{- $queryString := "" -}}
{{- range $k, $v := $params -}}
{{- if eq $queryString "" -}}
{{- $queryString = printf "%s=%s" $k (urlquery $v) -}}
{{- else -}}
{{- $queryString = printf "%s&%s=%s" $queryString $k (urlquery $v) -}}
{{- end -}}
{{- end -}}
{{- $bskyReq := printf "https://embed.bsky.app/oembed?%s" $queryString -}}
{{ template "fetchOEmbedHTML" $bskyReq }}
{{- else if in $url "linkedin.com" -}}
<div style="border: 1px solid #e5e7eb; border-radius: 12px; padding: 0 4px; overflow: hidden; max-width: {{ $width }}px; text-align: center;">
<iframe src="{{ $url | safeURL }}"
height="{{ $height }}"
width="{{ $width }}"
frameborder="0"
allowfullscreen=""
title="LinkedIn Post"
style="display: block; margin: 0 auto;"></iframe>
</div>
{{- else -}}
{{- errorf "Unsupported url format or social platform." -}}
{{- end -}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment