Last active
June 13, 2018 20:14
-
-
Save connerxyz/1f1a59c49593fa2bece5aafdebbdafcd to your computer and use it in GitHub Desktop.
A modular pattern for injecting your own template utils (i.e. functions) into Flask's template contexts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask | |
app = Flask(__name__) | |
# Register core.utils with all template contexts | |
import utils | |
@app.context_processor | |
def utils_context(): | |
return utils.registry |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{ foo() }} | |
{{ bar() }} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Define your utils here. Decorate anything you want made available to your templates with @util | |
""" | |
registry = {} | |
def util(func): | |
registry[func.__name__] = func | |
return func | |
@util | |
def foo(): | |
return "foo" | |
@util | |
def bar(): | |
return "bar" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment