-1

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) }}
zorglub76
  • 4,852
  • 7
  • 37
  • 46
  • Not sure the distinction you are making between flask templates and Jinja. From the [docs](https://flask.palletsprojects.com/en/2.1.x/tutorial/templates/): "Flask uses the Jinja template library to render templates." [Here's an example](https://stackoverflow.com/a/7226047/3874623) of doing this with flask/Jinja. – Mark Jun 29 '22 at 22:01

1 Answers1

1

Ok, I wasn't sure how Jinja was implemented into Flask, but actually (of course..) it's very simple.

So, you can pass functions the same way you pass variables to a template. Instead of mapping as Jinja does it (that func_dict and jinja_template.globals.update(func_dict)), you can pass them in the Flask's render_template() like this:

def get_percentage(part, whole):
  percentage = 0
  if part > 0 and whole > 0:
    percentage = 100 * part / whole
  return round(percentage)

@app.route("/")
def index():
  return render_template('index.html', projects=projects, get_percentage=get_percentage)

So, you can call that from the template:

{% set pct = get_percentage(one_number, other_number) %}

I hope this helps some other noob like me...

zorglub76
  • 4,852
  • 7
  • 37
  • 46