Skip to content

Instantly share code, notes, and snippets.

@masahitojp
Created December 17, 2010 04:41
Show Gist options
  • Save masahitojp/744497 to your computer and use it in GitHub Desktop.
Save masahitojp/744497 to your computer and use it in GitHub Desktop.
from flask import Flask, render_template
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
app = Flask(__name__)
# jinja2 custom filter
@app.template_filter()
def code_highlight(code, lang, style='default' , lineos=True):
lexer = get_lexer_by_name(lang, stripall=False)
formatter = HtmlFormatter(linenos=lineos, cssclass="source")
code = highlight(code, lexer, formatter)
style = '<style>' + \
HtmlFormatter(style=style
).get_style_defs('.highlight') \
+ '</style>'
return code+style
@app.route('/code/')
def code():
code = '''
if True:
print "Hello World"
else:
print "damn"
'''
return render_template('hello.html', name=name,
code=code)
if __name__ == '__main__':
app.debug = True
app.run()
<!doctype html>
<title>Hello from Flask</title>
<div class="highlight">
{{code|code_highlight("python")|safe}}
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment