# Jinja2

***

**1. Data Manipulation in Templates**

```python
{{ user.name.title() }}
```

**Explanation:** Modifies user's name to uppercase and concatenates it.

**2. Conditional Statements**

```python

<div data-gb-custom-block data-tag="if">

  <p>Administrator</p>

<div data-gb-custom-block data-tag="else"></div>

  <p>User</p>

</div>

```

**Explanation:** Displays "Administrator" if the user is an admin, otherwise "User".

**3. Loops and Iterations**

```python

<div data-gb-custom-block data-tag="for">

  <div>{{ post.title }}</div>

</div>

```

**Explanation:** Loops through a list of posts and displays the title for each post.

**4. Data Filtering**

```python

<div data-gb-custom-block data-tag="set" data-attribute='created_date'></div>

```

**Explanation:** Sorts a list of posts based on creation date.

**5. Custom Filters**

```python
@app.template_filter('duration')
def duration_filter(value):
    """Formats a duration in minutes into human-readable format."""
    return f"{value // 60}h {value % 60}m"
```

**Explanation:** Defines a custom filter to format a duration in minutes.

**6. Macros**

```python

<div data-gb-custom-block data-tag="macro">

  <div>
    <h2>{{ post.title }}</h2>
    <p>{{ post.content }}</p>
  </div>

</div>

```

**Explanation:** Defines a reusable block that renders a post's title and content.

**7. Includes**

```python

<div data-gb-custom-block data-tag="include" data-0='includes/sidebar.html'></div>

```

**Explanation:** Includes another template file into the current one.

**8. Inheritance**

```python

<div data-gb-custom-block data-tag="extends" data-0='base.html'></div>

<div data-gb-custom-block data-tag="block">

  <h1>Home</h1>

</div>

```

**Explanation:** Creates a template that inherits the layout from a base template.

**9. Static Asset Handling**

```python

<div data-gb-custom-block data-tag="static" data-0='style.css'></div>

```

**Explanation:** Generates the URL to a static asset, allowing for caching.

**10. Raw Data Output**

```python
{{ post.raw_content|safe }}
```

**Explanation:** Outputs raw data without escaping, allowing for dynamic content like HTML or JavaScript.

**11. URI Escaping**

```python
{{ url|uri_escape }}
```

**Explanation:** Escapes a URL string to protect against XSS attacks.

**12. HTML Escape**

```python
{{ post.title|escape }}
```

**Explanation:** Escapes HTML characters to prevent cross-site scripting.

**13. Date Manipulation**

```python

<div data-gb-custom-block data-tag="set"></div>

{{ now.strftime('%Y-%m-%d') }}
```

**Explanation:** Formats the current time using a specific date format.

**14. Mathematical Operations**

```python
{{ a + 5 }}
```

**Explanation:** Performs mathematical operations on template variables.

**15. Exception Handling**

```python

<div data-gb-custom-block data-tag="try">

  {{ undefined_variable }}

<div data-gb-custom-block data-tag="except"></div>

  {{ e }}

</div>

```

**Explanation:** Catches Jinja2 exceptions and allows for error handling.

**16. Default Values**

```python
{{ user.name|default('John Doe') }}
```

**Explanation:** Provides a default value if a variable is undefined.

**17. URL Building**

```python

<div data-gb-custom-block data-tag="set" data-0='view_post' data-1='view_post'></div>

```

**Explanation:** Generates a URL for a specific route.

**18. Form Rendering**

```python
<form action="{{ url_for('submit_form') }}" method="POST">
  <input type="text" name="name" />
</form>
```

**Explanation:** Renders a HTML form with the specified action and method.

**19. Delimiters**

```python
{# Comment using jinja delimiters #}
```

**Explanation:** Allows comments to be written within Jinja2 templates.

**20. Unicode Handling**

```python
{{ "你好"|to_unicode }}
```

**Explanation:** Converts a string to unicode to handle non-ASCII characters.

**21. Iteration Over Attributes**

```python

<div data-gb-custom-block data-tag="for">

  {{ key }}: {{ value }}

</div>

```

**Explanation:** Loops over the attributes of a dictionary object.

**22. Dictionaries in Templates**

```python
{{ dict.keys()|list }}
```

**Explanation:** Retrieves a list of keys from a dictionary.

**23. Callback Function Execution**

```python
{{ callback(arg1, arg2) }}
```

**Explanation:** Calls a specified callback function with arguments.

**24. String Joins**

```python
{{ ",".join(list) }}
```

**Explanation:** Concatenates elements of a list into a string using the specified separator.

**25. Object Attributes as Variables**

```python

<div data-gb-custom-block data-tag="set"></div>

```

**Explanation:** Assigns an object attribute to a template variable.

**26. Function Arguments**

```python
{{ square(x) }}
```

**Explanation:** Calls a function with a specified argument.

**27. Variable Assignment**

```python

<div data-gb-custom-block data-tag="set" data-x='5'></div>

```

**Explanation:** Assigns a value to a template variable.

**28. Comparison Operators**

```python

<div data-gb-custom-block data-tag="if">

  ...

</div>

```

**Explanation:** Compares template variables using comparison operators.

**29. Regular Expression Matching**

```python

<div data-gb-custom-block data-tag="if" data-0='[a-z]+' data-1='[a-z]+'>

  ...

</div>

```

**Explanation:** Checks if a string matches a regular expression.

**30. Boolean Operations**

```python

<div data-gb-custom-block data-tag="if">

  ...

</div>

```

**Explanation:** Performs boolean operations on template variables.

**31. List Operations**

```python
{{ list.sort() }}
```

**Explanation:** Sorts a list in-place.

**32. Dictionary Operations**

```python
{{ dict.get('key', default_value) }}
```

**Explanation:** Retrieves a value from a dictionary, returning a default value if the key is not found.

**33. Formatted String Literal**

```python
{{ f"Hello, {name}!" }}
```

**Explanation:** Formats a string using the f-string syntax.

**34. Call a Class Method**

```python
{{ object.method(argument) }}
```

**Explanation:** Calls a method on an object and passes an argument.

**35. Access a Class Attribute**

```python
{{ object.attribute }}
```

**Explanation:** Accesses an attribute of a class.

**36. Create an Object**

```python
{{ object = Class(argument) }}
```

**Explanation:** Creates an object of a class and passes an argument.

**37. Loop Over a Range**

```python

<div data-gb-custom-block data-tag="for" data-0='5' data-1='5' data-2='5' data-3='5' data-4='5' data-5='5' data-6='5' data-7='5' data-8='5' data-9='5' data-10='5' data-11='5'>

  {{ i }}

</div>

```

**Explanation:** Iterates through a range of numbers.

**38. Check if Variable is Defined**

```python

<div data-gb-custom-block data-tag="if">

  ...

</div>

```

**Explanation:** Verifies whether a variable is defined.

**39. Load a Template from a File**

```python

<div data-gb-custom-block data-tag="from" data-0='path/to/template.html'></div>

```

**Explanation:** Imports a template from a file and makes all its variables available.

**40. Assign a Template Variable to Global Namespace**

```python

<div data-gb-custom-block data-tag="set"></div>

```

**Explanation:** Assigns a variable to the global namespace, making it available throughout the application.

**41. Access Environment Variables**

```python
{{ getenv('USER') }}
```

**Explanation:** Retrieves an environment variable.

**42. Call a Callback Function with Keyword Arguments**

```python
{{ callback(arg1=1, arg2='value') }}
```

**Explanation:** Calls a callback function with specific keyword arguments.

**43. Execute Custom Code**

```python

<div data-gb-custom-block data-tag="with" data-0='README.md'>

  {{ f.read() }}

</div>

```

**Explanation:** Executes custom Python code within the template.

**44. Create a Custom Context**

```python

<div data-gb-custom-block data-tag="with" data-0='Alice' data-name='Alice'>

  ...

</div>

```

**Explanation:** Creates a temporary context with modified values.

**45. Access Function Annotations**

```python

<div data-gb-custom-block data-tag="set" data-0='input_type' data-1='input_type' data-2='input_type' data-3='input_type'></div>

```

**Explanation:** Retrieves the type annotation for a function input parameter.

**46. Call a Function with Positional Arguments**

```python
{{ function(1, 'value', True) }}
```

**Explanation:** Calls a function with positional arguments.

**47. Index into a List or Tuple**

```python
{{ list[index] }}
```

**Explanation:** Accesses an element of a list or tuple using an index.

**48. Slice a List or Tuple**

```python
{{ list[start:end] }}
```

**Explanation:** Slices a list or tuple to create a new list or tuple.

**49. Get the Length of a List or Tuple**

```python
{{ len(list) }}
```

**Explanation:** Retrieves the number of elements in a list or tuple.

**50. Combine Multiple Templates**

```python

<div data-gb-custom-block data-tag="include" data-0='header.html'></div>

<div data-gb-custom-block data-tag="include" data-0='content.html'></div>

<div data-gb-custom-block data-tag="include" data-0='footer.html'></div>

```

**Explanation:** Combines multiple templates into a single cohesive template.

**51. Access a Dictionary Value**

```python
{{ dictionary['key'] }}
```

**Explanation:** Retrieves the value associated with a key in a dictionary.

**52. Get the Keys of a Dictionary**

```python
{{ dictionary.keys() }}
```

**Explanation:** Retrieves a list of the keys in a dictionary.

**53. Get the Values of a Dictionary**

```python
{{ dictionary.values() }}
```

**Explanation:** Retrieves a list of the values in a dictionary.

**54. Check if a Key Exists in a Dictionary**

```python

<div data-gb-custom-block data-tag="if" data-0='key'>

  ...

</div>

```

**Explanation:** Checks if a key exists in a dictionary.

**55. Iterate Over a Dictionary**

```python

<div data-gb-custom-block data-tag="for">

  ...

</div>

```

**Explanation:** Iterates over the key-value pairs in a dictionary.

**56. Get the First Item in a List or Tuple**

```python
{{ list[0] }}
```

**Explanation:** Retrieves the first item in a list or tuple.

**57. Get the Last Item in a List or Tuple**

```python
{{ list[-1] }}
```

**Explanation:** Retrieves the last item in a list or tuple.

**58. Reverse a List or Tuple**

```python
{{ list[::-1] }}
```

**Explanation:** Creates a new list or tuple with the elements in reverse order.

**59. Sort a List or Tuple**

```python
{{ list.sort() }}
```

**Explanation:** Sorts a list or tuple in place.

**60. Filter a List or Tuple**

```python
{{ list|filter(lambda item: item > 0) }}
```

**Explanation:** Creates a new list or tuple containing only the items that pass a filter condition.

**61. Map a List or Tuple**

```python
{{ list|map(lambda item: item + 1) }}
```

**Explanation:** Creates a new list or tuple by applying a function to each item in the original list or tuple.

**62. Combine Multiple Lists or Tuples**

```python
{{ list1 + list2 }}
```

**Explanation:** Combines multiple lists or tuples into a single list or tuple.

**63. Check if a Value is in a List or Tuple**

```python

<div data-gb-custom-block data-tag="if">

  ...

</div>

```

**Explanation:** Checks if a value is contained in a list or tuple.

**64. Create a Set**

```python
{{ set() }}
```

**Explanation:** Creates a new empty set.

**65. Add an Item to a Set**

```python
{{ set.add(item) }}
```

**Explanation:** Adds an item to a set.

**66. Iterate Over a Set**

```python

<div data-gb-custom-block data-tag="for">

  ...

</div>

```

**Explanation:** Iterates over the items in a set.

**67. Check if a Set Contains an Item**

```python

<div data-gb-custom-block data-tag="if">

  ...

</div>

```

**Explanation:** Checks if a set contains a specific item.

**68. Intersect Two Sets**

```python
{{ set1.intersection(set2) }}
```

**Explanation:** Creates a new set containing the elements that are common to both sets.

**69. Union Two Sets**

```python
{{ set1.union(set2) }}
```

**Explanation:** Creates a new set containing all the elements from both sets.

**70. Difference Between Two Sets**

```python
{{ set1.difference(set2) }}
```

**Explanation:** Creates a new set containing the elements that are in set1 but not in set2.

**71. Symmetric Difference Between Two Sets**

```python
{{ set1.symmetric_difference(set2) }}
```

**Explanation:** Creates a new set containing the elements that are in either set1 or set2 but not in both.

**72. Create a Frozen Set**

```python
{{ frozenset() }}
```

**Explanation:** Creates a new frozen set.

**73. Iterate Over a Frozen Set**

```python

<div data-gb-custom-block data-tag="for">

  ...

</div>

```

**Explanation:** Iterates over the items in a frozen set.

**74. Check if a Frozen Set Contains an Item**

```python

<div data-gb-custom-block data-tag="if">

  ...

</div>
```

**Explanation:** Checks if a frozen set contains a specific item.

**75. Convert a Set to a List**

```python
{{ list(set) }}
```

**Explanation:** Converts a set to a list.

**76. Convert a Tuple to a List**

```python
{{ list(tuple) }}
```

**Explanation:** Converts a tuple to a list.

**77. Convert a Dictionary to a List of Tuples**

```python
{{ list(dictionary.items()) }}
```

**Explanation:** Converts a dictionary to a list of tuples, where each tuple represents a key-value pair.

**78. Convert a Dictionary to a List of Lists**

```python
{{ list(dictionary.values()) }}
```

**Explanation:** Converts a dictionary to a list of lists, where each list contains the values for a key in the dictionary.

\*\*79
