Beginners' Guide: Variables and Loop Syntax in Django Template Engine Jinja2
This article introduces the core syntax of variables and loops in the Django template engine Jinja2. The template engine combines backend data with HTML templates to generate web pages. As Django's default engine, Jinja2 is the focus here, with emphasis on variables and loops. Variable syntax: Variables are enclosed in double curly braces {{}}. They support strings, numbers, booleans, and lists (displayed directly). Dictionaries can be accessed using dot notation (.) or square brackets ([]), such as {{ user.name }} or {{ user["address"]["city"] }}. Note that undefined variables will cause errors, and variables in templates are not modifiable. Loop syntax: Use {% for variable in list %} to iterate. It is accompanied by forloop.counter (for counting), first/last (for marking the first and last elements), and {% empty %} to handle empty lists. Examples include looping through lists or lists of dictionaries (e.g., each dictionary in a user list). Summary: Mastering variables and loops enables quick data rendering. Subsequent articles will cover advanced topics such as conditions and filters.
Read More