ChatGPT told me that:
In Jinja2, if an expression is enclosed in quotes (single or double), it is treated as a literal string, and the entire content, including the expression, will be output as-is. Jinja2 does not parse or evaluate expressions within quoted strings.
However I tested the following template:
{% set name = "Jason" -%}
Name: "{{ name }}"
The output is
Name: "Jason"
While according to ChatGPT it should be:
Name: {{ name }}
So is ChatGPT wrong? What is the behavior of double/single quote in jinja2?
ChatGPT told me that:
In Jinja2, if an expression is enclosed in quotes (single or double), it is treated as a literal string, and the entire content, including the expression, will be output as-is. Jinja2 does not parse or evaluate expressions within quoted strings.
However I tested the following template:
{% set name = "Jason" -%}
Name: "{{ name }}"
The output is
Name: "Jason"
While according to ChatGPT it should be:
Name: {{ name }}
So is ChatGPT wrong? What is the behavior of double/single quote in jinja2?
Share Improve this question asked Nov 21, 2024 at 3:19 codewarriorcodewarrior 99110 silver badges30 bronze badges2 Answers
Reset to default 1So is ChatGPT wrong?
No.
When you write:
Name: "{{ name }}"
The quotes are not part of the Jinja template expression. They are literal text in your document. Jinja only evaluates expressions within {{...}}
markers. If you had written this:
Name: {{ "name" }}
Jinja would interpret "name"
as a literal string and the output would be:
Name: name
And if you had written:
Name: "{{ "name" }}"
The output would be:
Name: "name"
ChatGPT is partially correct. It only happens within Jinja tags, not the whole source of a Jinja2 template. When using quotes in HTML, Jinja doesn't replace them outside of tags.
If you do want to escape Jinja templating, you have other ways to do it:
- Output a string with the code:
{{ "{{ name }}" }}
- Use HTML entities:
{{ name }}
- Use the Jinja {% raw %} tag:
(should you want to print{% raw %} {{ name }} {% endraw %}
{{ endraw }}
, use another escaping method)