YouTip LogoYouTip

Flask Template Rendering Api

# Flask Template Rendering API Flask uses the **Jinja2** template engine to render dynamic HTML pages by embedding Python data directly into HTML templates. By default, Flask looks for template files in a directory named `templates/` located at the root of your project directory. --- ## The Core API: `render_template` The most frequently used template rendering function is `render_template`. It loads a template file from your templates directory, renders it with the provided context, and returns the generated HTML as a string. ### Parameters | Parameter | Type | Description | | :--- | :--- | :--- | | `template_name_or_list` | `str` / `list` | The filename of the template (relative to the `templates/` folder), or a list of template names (Flask will render the first one that exists). | | `**context` | Keyword Arguments | Arbitrary variables passed directly to the template (e.g., `title="Home"`, `user=user_obj`). | --- ## Complete Template Rendering API Reference Flask provides several functions to handle different rendering scenarios, such as rendering from strings or streaming large datasets. | Function | Description | | :--- | :--- | | `render_template(template_name_or_list, **context)` | Renders a template from a file and returns the HTML as a string. | | `render_template_string(source, **context)` | Renders a template directly from a string. Useful for dynamic or inline templates. | | `stream_template(template_name_or_list, **context)` | Streams a template from a file, returning a generator. Ideal for rendering large pages efficiently. | | `stream_template_string(source, **context)` | Streams a template directly from a string. | | `get_template_attribute(template_name, attribute)` | Retrieves a specific macro or variable from a template, allowing you to call Jinja2 macros directly from Python code. | --- ## Built-in Objects in Templates Flask automatically injects several global variables and helper functions into the template context. You can use these directly in your templates without explicitly passing them from your Python code: | Object | Description | | :--- | :--- | | `request` | The current HTTP request object (`flask.request`). | | `session` | The active session object for storing user data across requests (`flask.session`). | | `g` | The application context global variable for temporary request-level storage (`flask.g`). | | `config` | The current Flask application configuration dictionary (`app.config`). | | `url_for` | The helper function used to dynamically generate URLs for routes. | | `get_flashed_messages` | The function used to retrieve messages flashed via `flash()`. | --- ## Code Examples The following example demonstrates how to use standard rendering, inline string rendering, and template streaming in a Flask application. ```python from flask import Flask, render_template, render_template_string, stream_template app = Flask(__name__) # Mock function for streaming example def get_10k_items(): return [f"Item {i}" for i in range(1, 10001)] @app.route("/") def index(): # Render a standard HTML template file with context variables return render_template( "index.html", title="YouTip Home", posts=[ {"id": 1, "title": "Getting Started with Flask"}, {"id": 2, "title": "Mastering Jinja2 Templates"} ] ) @app.route("/inline") def inline_template(): # Render a template directly from an inline string return render_template_string("""

Hello, {{ name }}!

Welcome to YouTip.

""", name="Developer") @app.route("/stream") def stream_large_page(): # Stream a large page to the client chunk-by-chunk as it generates return stream_template( "large_report.html", items=get_10k_items() ) ``` --- ## Best Practices and Considerations 1. **Directory Structure**: Always ensure your templates are placed in a folder named `templates` at the root level of your Flask application (or blueprint), unless you have explicitly configured a custom template folder. 2. **Security (XSS Protection)**: Jinja2 automatically escapes HTML characters in variables passed to templates to prevent Cross-Site Scripting (XSS) attacks. If you intentionally want to render raw HTML, use the `| safe` filter in your template or wrap the string in `markupsafe.Markup` in your Python code. 3. **Avoid `render_template_string` with User Input**: Never pass untrusted user input directly into the template string of `render_template_string` (e.g., `render_template_string(f"Hello {user_input}")`). This leads to **Server-Side Template Injection (SSTI)**. Instead, pass user input safely via context variables: `render_template_string("Hello {{ name }}", name=user_input)`.
← Flask Stream Helpers ApiFlask Message Flashing Api β†’