Getting Started with Flask Templates: Jinja2 Variables and Control Structures
This article introduces the basic usage of the Jinja2 engine in the Flask template system, which helps dynamically display data on web pages. The core content includes: 1. **Jinja2 Variables**: Data is passed from the backend view function via `render_template`, and variables in the template are rendered using `{{ variable_name }}`. It supports various types such as strings, numbers, lists, and dictionaries. An example demonstrates variable rendering through user information (name, age, hobby list). 2. **Control Structures**: Conditional judgments use `{% if ... %}` (e.g., checking if age is adult), and loops use `{% for ... %}` (iterating over a list). The `loop` variable (e.g., `loop.first`, `loop.last`) is utilized to optimize iteration logic. 3. **Filters**: Variables are processed using the `|` syntax, such as `upper` for uppercase conversion, `round` for rounding, and `safe` for rendering HTML (with security precautions noted). The article summarizes the core methods to achieve page dynamicity through variables, control structures, and filters, laying the foundation for advanced template features like inheritance and macros.
Read More