I have a Gist file written in different languages all do the same thing.
So, I would like to create a language select option similar to Google docs documentation.
Is it possible to create such a wrapper class that accepts a Gist script tag and display as above?
As in embed single file, I tried different query command like <script src=”https://gist.github.com/gistid.js?language=python”>, but none of them work.
Advertisement
Answer
This is the processing code that I ended up with.
With some CSS + javascript hide and toggle logic, it would work like google docs documentation.
I’d appreciate it if anyone updates this answer, with css or js.
import requests from bs4 import BeautifulSoup def render_gist_by_file(gist_id): result = requests.get(f'https://gist.github.com/{gist_id}.js', headers=git_credential) if result.text.startswith("<!DOCTYPE html>"): return None result = result.text result = result.replace("\/", "/").replace("\&", "&").replace("\$", "$").replace("\<", "<").replace("\`", "`").replace("\n", "n").replace('\"', '"') result = html.unescape(result) result = result.split("document.write('")[-1][:-3] bs = BeautifulSoup(result, "html.parser") for tag in bs.find_all(class_="gist"): file_box = tag.find(class_="file-box") root = tag.find(class_="file-box") toggle_div = bs.new_tag('div', attrs={"class": "gist-meta"}) for i, d in enumerate(tag.find_all(class_="file")): d["class"] = f"file gist-toggle gist-id-{gist_id}" if i != 0: file_box.append(d) # combine to first table for d in tag.find_all(class_="gist-meta"): siblings = list(d.next_elements) file_id, file_name = siblings[4].attrs["href"].split("#")[-1], siblings[5] gist.file_names.append(file_name) toggle_a = bs.new_tag('a', attrs={"id": file_id, "class": f"gist-toggle gist-id-{gist_id}", "onclick": f"toggle('gist-id-{gist_id}', '{file_id}')", "style": "padding: 0 18px"}) toggle_a.append(file_name) toggle_div.append(toggle_a) d.extract() # remove bottom nav root.insert(0, toggle_div) for d in islice(tag.find_all(class_="gist-file"), 1, None): d.extract() # remove except first gist.html = str(bs) return gist