Jinja Literal Expression: Strings
n
"...") or single quotes ('...'). They are a fundamental type of data used to represent text within your templates. Strings are essential for displaying static text, passing arguments to filters and functions, and performing comparisons.nn
nn
How It Works
nJinja2 treats any sequence of characters within matching quotes as a string. There is no functional difference between using single or double quotes, but you should be consistent in your usage. This allows you to easily include the other type of quote within your string without needing to escape it (e.g., "This is a string with a 'single' quote.").nnStrings can be used in various parts of a template, including:n
- n
- For direct output using
{{ ... }}. - As the value for a variable using
{% set ... %}. - As arguments to filters or functions (e.g.,
"my string"|upper). - In conditional statements (e.g.,
{% if user == "admin" %}).
n
n
n
n
n
Syntax
n
{{ "Hello World" }}n{{ 'Hello World' }}n{% set my_message = "Welcome to Jinja2" %}
nn
nn
Demonstration with Code Samples
nHere are some practical examples of how to use string literals in a Jinja2 application.n
1. Displaying a Simple String
nThis is the most basic use case, where you simply want to output a static piece of text.nnJinja2 Templaten
<h1>{{ "Welcome to the website!" }}</h1>n<p>{{ 'Please navigate using the links above.' }}</p>
nExplanation: Both examples directly output the text enclosed in the quotes. You can see that both single and double quotes produce the same result.nn
nn
2. Using a String in a Conditional Statement
nStrings are commonly used for comparison to control the flow of your template’s logic.nnJinja2 Templaten
{% set user_role = 'guest' %}n{% if user_role == 'admin' %}n <p>Hello, admin! You have full access.</p>n{% else %}n <p>Hello, guest! Please log in to gain more access.</p>n{% endif %}
nExplanation: The template checks if the value of the `user_role` variable is equal to the string literal `’admin’`. Since it is not, the `else` block is rendered.nn
nn
3. Passing a String as a Filter Argument
nYou can use a string literal as an argument to a filter to modify a variable’s output, for example, to make a default value uppercase.nnJinja2 Templaten
{% set status_message = None %}n<p>Current Status: {{ status_message | default("No Status") | upper }}</p>
nExplanation: The `default` filter is given the string literal `”No Status”` as an argument. Since `status_message` is `None`, the filter returns the string `”No Status”`, which is then passed to the `upper` filter to be displayed in all caps.nn
