Is there a way to define a function in Python file, and then use it in the template in Flask?
AFAIK, you can do that in Jinja, but I'm not sure if it's doable in Flask. Jinja example:
def hello_world():
return "hello world from within the function"
def multiply(x, y):
return str(x * y)
func_dict = {
"hello_world": hello_world,
"multiply": multiply,
}
def render(template):
env = Environment(loader=FileSystemLoader("/srv/templates/"))
jinja_template = env.get_template(template)
jinja_template.globals.update(func_dict)
template_string = jinja_template.render()
return template_string
And then in template, you use:
Calling the 'hello_world' function:
{{ hello_world() }}
Calling the 'multiply' function:
{{ multiply(2, 2) }}