Call Custom python function in jinja

I want to create Custom python function in custom app to call it in jinja print format .

I checked jinja.py and see only make available limited methods of frappe:
https://github.com/frappe/frappe/blob/develop/frappe/utils/jinja.py#L84

How I can call my custom method in jinja?

Is it possible to do it from my custom app or I need to add my function in jinja.py?

@Mohammed_Redha can you explain the use case?

I have a specific use case!

For any given document, you can print the Transaction date:

{{ doc.get_formatted("transaction_date") }}

However in my case, I need each date element to fit a pre-printed paper format we have, with the date box pre-formatted. I need to print each element of the date separately. How can I extract the Year, assign to a variable, then the Month to assign to a variable, then the Day to assign to a third variable. Each variable is then printed by itself.

I have tried using datetime objects, and converting to strings using Jinja correct syntax, but no luck.

sir can you help me with, how to call white-list function in print format. sir i have return long in white-list function but i not able to print that value in print format.
please help me sir.

Thanks and regards

A bit outdated, but I managed to solve this one with help from another post, here are point to point instructions:

It’s necessary to whitelist your function so it can be called successfully from a custom Print Format.

1.- Develop your function in any python file ( .py ) within your custom app, and add the following decorator above the function:

@frappe.whitelist()

2.- If the file where you defined the function is /apps/your-app/your-app/your_module.py and the function is called my_function () the route that you will use is this: your_app.your_module.my_function

3.- Add the following to hooks.py

jenv = {
    “methods”: [
        “my_function:your_app.your_module.my_function”
    ]
}

Please note that the definition to pass your defined Python function to the Jinja environment is defined by the following structure:

[virtual_environment_desired_function_name]:[route_and_name_of_python_function]Preformatted text

4.- On your terminal, execute the following commands:

bench restart
bench migrate

Even though bench migrate is not required, some reports exist about it improving the desired functionality outcome.

5.- On the custom Print Format where you wish to access your function, execute it in the following manner:

{{ virtual_environment_desired_function_name() }}

You may pass arguments to it, and you will receive the returned results (if such is the purpose of your function)

Main Source: Call your own functions in Frappe

8 Likes