Jinja Operator: () (Parentheses)
n
() operator in Jinja2 is used to call a callable object, such as a function, a method, or a macro. Just like in Python, you place the parentheses after the name of the callable to execute it. You can pass arguments inside the parentheses to customize the function’s behavior, using both positional and keyword arguments. This is how you execute logic and reuse code within your templates.nn
nn
How It Works
nThe parentheses operator is the core mechanism for dynamic execution in Jinja2. It allows you to interact with the functions and methods you’ve passed from your Python application and with macros defined in the template itself.n
Syntax
n
{{ callable_name() }}n{{ callable_name(arg1, arg2='value') }}
n
- n
callable_name: The name of the function, method, or macro to be called.arg1: A positional argument.arg2='value': A keyword argument.
n
n
n
nn
nn
Demonstration with Code Samples
nHere are some practical examples of how to use the () operator in a Jinja2 application.n
1. Calling a Method on an Object
nThis is a very common use case for objects passed from your Python application.nnJinja2 Templaten
<p>Product: {{ product.get_formatted_name() }}</p>n<p>Price: {{ product.calculate_discounted_price(discount=0.1) }}</p>
nExplanation: The first line calls the get_formatted_name() method on the product object. The second line calls a method that accepts a keyword argument discount to calculate a new price.nn
nn
2. Using Built-in Jinja2 Functions
nJinja2 provides several built-in functions that you can call with (), such as range().nnJinja2 Templaten
<ul>n{% for i in range(5) %}n <li>Item {{ i }}</li>n{% endfor %}n</ul>
nExplanation: The range(5) function call generates a sequence of numbers from 0 to 4, which the for loop then iterates over.nn
nn
3. Calling a Macro
nMacros are reusable blocks of code within a template, similar to functions. You call them using parentheses.nnJinja2 Macro Definition (macros.html)n
{% macro render_button(text, url) %}n <a href="{{ url }}" class="btn">{{ text|upper }}</a>n{% endmacro %}
nJinja2 Template (where macros.html is imported)n
{% from 'macros.html' import render_button %}nn<p>You can access your account from here:</p>n{{ render_button('Login', '/login') }}
nExplanation: After importing the macro, the render_button() call executes the macro with the provided positional arguments ('Login' and '/login'), rendering the full HTML <a> tag.nn
