Skip to content

Instantly share code, notes, and snippets.

@8bit-pixies
Created January 28, 2013 05:49
Show Gist options
  • Save 8bit-pixies/4653335 to your computer and use it in GitHub Desktop.
Save 8bit-pixies/4653335 to your computer and use it in GitHub Desktop.
tangledpython
#module to do a clean up for tangle.js
import markdown
import re
import ast
import yaml
import jinja2
import os
"""
[VARIABLE[FORMULA or VALUE]format,attributes,text]
format comes first and starts with '%'
attributes is next and starts with '{', ending with '}'
otherwise is just text
"""
md_text = """
---
name : Toggle
toggleT: {'toggleTrue':'true', 'toggleFalse':'false', 'class':'TKToggle TKSwitch'}
---
toggle this: [toggleT{'value_init':'true'}]so this is [indic{'update':'toggleT ? "toggle true" : "toggle false"'}]
"""
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=True)
class Tangle:
"""
create from the dictionary of items,
all the javascript variables
"""
def __init__(self,dicts):
self.initialize = ""
self.update = ""
for dict_item in dicts:
if isinstance(dicts[dict_item],dict):
if 'value_init' in dicts[dict_item].keys():
self.initialize += "this.%s=%s;" % (dict_item,dicts[dict_item]['value_init'])
if 'update' in dicts[dict_item].keys():
#do not stick this in a string
self.update += "this.%s=%s;" % (dict_item,''.join([add_this(x) for x in re.split("""(['"].*?['"])""",dicts[dict_item]['update'])]))
def add_this(string):
print string
if '"' != string[:1] and "'" != string[:1]:
return re.sub(r'([a-zA-Z]\w+)',r'this.\1',string)
else:
return string
def insert_Attribute(string,attr,search):
"""
for inserting attributes to the span element for:
determine the class whether you scrub
determine the format (limit to X decimal points)
"""
search_long = r"data-var='%s'" %(search)
if search_long in string:
re_search = re.split(r"(data-var='%s')" %(search),string)
re_search.insert(1,'%s ' % (attr))
return ''.join(re_search)
else:
return string
def insert_Toggle(string,toggle,search):
"""
for inserting toggleable things
"""
search_long = r"data-var='%s'" %(search)
if search_long in string:
re_search = re.split(r"(data-var='%s'.*?>)" %(search),string)
re_search.insert(2,'%s ' % (toggle))
return ''.join(re_search)
else:
return string
def span_Toggle(dicts):
"""
<span>False</span> <!--false-->
<span>True</span> <!-- true -->
"""
text = """<span>%s</span><span>%s</span>"""
return text % (dicts['toggleFalse'],dicts['toggleTrue'])
#please make this a class!
#step one get all the data variables
data = re.findall(r'\[(.*?\{.*?\}.*?)\]',md_text)
text_md = re.findall(r'---(.*)---(.*)',md_text,re.DOTALL)
dicts=yaml.load(text_md[0][0].strip('\n'))
for x in data:
text = re.search(r'\w+',x).group()
var = re.search(r'(\{.*?\})',x).group()
if text not in dicts.keys():
dicts[text]=ast.literal_eval(var)
else:
dicts[text].update(ast.literal_eval(var))
#start adding the html tags in the text
#for this we add the following format to the string:
#<span data-var="VARIABLE">TEXT</span>
#need to add the class; however this has to be flexible so that it is open to
#other classes which may pop up in the future
regex = re.compile(r'\[(.*?)\{.*?\}(.*?)\]')
span_md = regex.sub(r"<span data-var='\1'>\2</span>",text_md[0][1].strip('\n'))
#class="TKAdjustableNumber"
#build the body
for x in dicts:
if isinstance(dicts[x],dict):
if 'class' in dicts[x].keys():
span_md=insert_Attribute(span_md,'class="'+dicts[x]['class']+'"',x)
if 'format' in dicts[x].keys():
span_md=insert_Attribute(span_md,'data-format='+dicts[x]['format'],x)
if 'toggleTrue' in dicts[x].keys(): # or 'toggleFalse' in dicts[x].keys()
span_md=insert_Toggle(span_md,span_Toggle(dicts[x]),x)
js_tangle = Tangle(dicts)
#build the javascript
#get the id of the particular section
#we would look at text_md[0][0] for the relevant information
text = """
function setUpTangle () {
var element = document.getElementById("%s");
var tangle = new Tangle(element, {
initialize: function () {
%s
},
update: function () {
%s
}
});
}
""" % (dicts['name'],js_tangle.initialize,js_tangle.update)
html ="""
<div id='%s'>
%s
</div>
""" % (dicts['name'],markdown.markdown(span_md))
print text
print html
#attach to the template
#p = jinja_env.get_template("outline.html").render(slides = m)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment